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?
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...)
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:
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:
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