Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

How can I include * inside a string?

Here is my code:

#!/bin/bash
# This is a simple calculator using select statement
echo -n 'Insert 1st operand: '
read first
echo -n 'Insert 2nd operand: '
read second
echo 'Select an operator:'
operators="+ - * /"
select op in $operators
do let "result=${first}${op}${second}"
   break
done
echo -e "Result = $result"

When I run this code, * will list all files in current directory as select choices. I tried to escape it with \* but it doesn't work.

share|improve this question

3 Answers 3

up vote 3 down vote accepted

The shall expands its parameters. But then select expands its parameters too. The shell expands \* to just *, which doesn't help, since select then expands that *. You need something that expands to \*, which would be \\*.

Alternatively, just use:
select op in + - \* /;
or:
select op in "$operators"

share|improve this answer
    
+1 Thanks. This works perfectly :) –  Eng.Fouad Oct 5 '11 at 19:04

First you can put $operator with double quotes to be sure that there is no interpretation. Select display correctly the list of parameters BTW the end of code doesn't work as expected : it display the first and the second operand but not the operator

share|improve this answer

Arrays help out quite often in shell scripting when you experience difficulty using a string you've constructed dynamically.

$ operators=( + - '*' / )
$ PS3="choice? "
$ select o in "${operators[@]}"; do echo "$o $REPLY"; done
1) +
2) -
3) *
4) /
choice? 1
+ 1
choice? 2
- 2
choice? 3
* 3
choice? 4
/ 4
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.