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.

link|improve this question

feedback

4 Answers

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"

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

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

link|improve this answer
feedback

In shell scripts quoting when setting a variable is not enough - you should also quote when you use it. So something like this will solve your expansion problems:

select op in "$operators"

However, this won't work your script work. The select statement expects a list of words, but you give it just a single string "+ - * /". To make it work, you have to use something like this:

select op in + - \* /
link|improve this answer
feedback

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
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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