Passing asterisk As A Parameter

I have written a Shell Script Program which accepts 3 parameters as shown below:

./calc 20 + 2

in the above line ./calc is the Shell Script itself with 3 parameters, namely:

20
+
and 2.

Well, now let's look inside the Script:

result=$1$2$3
echo $result

The output will be as per our expectation:

22

But well, let's change the sign in the 2nd parameter being passed:

./calc 20 - 2
./calc 20 / 2

All those there examples have no issues so far!

But when we pass * as a parameter

./calc 20 * 2

things go bad!

Instead of *, the result of "ls *" command or simply the directory list gets passed to the variable: $2.

So, how can I make this Calculator program a user friendly one? I have been suggested to use '*' (I have not tried it yet, however) but it doesn't seem to be a User Friendly Way of writing any script or program, does it?

Thanks!

Dev.

Escape the asterisk

./calc 20 \* 2

try

./calc bill \* gates

and you'll get a ls listing again. Escaping the asterisk only seems to work on numerals. Does anyone know a workaround?

If you have the bc package installed, this script works:

#!/bin/sh
echo "$@" | bc 

But you do have to quote the asterisk as suggested: calc 20 \* 2

BTW, try using your script in a directory that has no files. That is, try this:

mkdir empty
cd empty
../calc 20 * 2
cd ..
rmdir empty

If typing an extra command before & after you're done using the 'calc' utility is acceptable, you could type "set -f" first... ("set +f" to set it back when you're done)...
(Unfortunately, putting this command inside your script won't work, since by the time the script is executed, the * special character will already be expanded...)

Well, I tried this code segment:

./calc 10 '*' 5

and also this one

./calc 10 "*" 5

and both of them worked. But it is not user-friendly, is it?

One thing you might try is using the double parens math workings of bash. Quite cool and is readable, and it avoids your shell expansion problem. Secondarily, a "here" document with the "dc" program is how I used to do it. e.g.:

dc <<EOF
2 20 * p
EOF
will produce 40 as output

Using the double-parens syntax of bash, one can do this:

$i=0
((i=2*20))
echo $i <-- produces 40

Kinda cool, huh?

Are you doing this as an exercise, a learning experience, or to get usable tool?

If the latter, have you tried the bc package? It does nearly what you are trying to do.
I entered "5 * 10", it returned 50, I entered "quit" to get back to my shell prompt:

bc -q
5 * 10
50
quit 

Hi.

That depends on who your friends are :slight_smile:

You could try another accepted symbol:

This means more work for you in the script -- test $2 for an "x", substitute a "*" and continue with (( ... )), bc, etc. If one is trying to make a client happy, then there is often more such work required from the provider ... cheers, drl