Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid expansion of * in bash builtin function let

I have a problem with a bash script. I have to use the operator * to multiplicate. Instead the script bugs me with expansion and using as operator the name of the script itself. I tried with single quotes but it doesn't work :( Here's the code

#!/bin/bash -x

# Bash script that calculates an arithmetic expression
# NO PRECEDENCE FOR OPERATORS
# Operators: + - * 

if [ "$#" -lt "3" ]
then 
    echo "Usage: ./calcola.scr <num> <op> <num> ..."
    exit 1
fi

result=0
op=+
j=0

for i in "$@"
do
    if [ "$j" -eq "0" ]
    then
        # first try
        #result=$(( $result $op $i )) 

        # second try
        let "result$op=$i"

        j=1
    else
        op=$i
        j=0
    fi
done

echo "Result is $result"

exit 0
like image 614
gc5 Avatar asked Dec 06 '22 07:12

gc5


2 Answers

If you don't need "* expansion" (referred as "globbing" in general) at all for your script, just start it with "-f"; you can also change it during run time:

mat@owiowi:/tmp/test$ echo *
A B
mat@owiowi:/tmp/test$ set -f
mat@owiowi:/tmp/test$ echo *
*
mat@owiowi:/tmp/test$ set +f
mat@owiowi:/tmp/test$ echo *
A B
like image 169
MatthieuP Avatar answered Jan 02 '23 00:01

MatthieuP


If "op" is "*", it will be expanded by the shell before your script even sees it. You need to choose something else for your multiplication operator, like "x", or force your users to escape it by putting it in single quotes or preceeding it with a backslash.

If the terms of the exercise allow it, maybe you should try using "read" to get the expression from standard input instead of getting them from the command line.

like image 33
Paul Tomblin Avatar answered Jan 02 '23 02:01

Paul Tomblin