How do I run the script: ./script.sh 1 \* 2

Eventually: ./script.sh 1 '*' 2

How does my script look like:

args="$@" # the first line of the script
echo "$args = $result"

Does it work: yes

What I want to achieve: I want to use expr instead of $((...))

Something like:

args="$@" # the first line of the script
result=`expr $args`
echo "$args = $result"

It works fine for input arguments like 1 + 2, but it does not work properly (or, more likely, at all: expr: syntax error) for asterisk (star) symbol. I'd like to know why this does not work as desired and how should I fix this.

Script like this: expr "$@" does work - I just do not understand what is going on when I assign $@ to a variable.


Why your script doesn't work

Your script as is right now performs wildcard expansion to replace wildcard with all files in your current working directory. This is evident if you add set -x option to the top of the script.

$ ./expr_script.sh 2 '*' 2
+ args='2 * 2'
++ expr 2 -23.txt add_location_name.py expr_script.sh kusalananda 'Movie A (2014)' 'Movie B (2016)' one.test popup_script.sh somefile2.txt somefile.txt somethings texts three.test turnSignal.v two.test 2
expr: syntax error
+ result=
+ echo '2 * 2 = '
2 * 2 = 

How to fix it

You won't need filename expansion in the arithmetic script, hence disable glob expansion with set -f option.

set -f
##set -x
args="$@" # the first line of the script
result=$(expr $args)
echo "$args = $result"

This works:

$ ./expr_script.sh 2 '*' 2
2 * 2 = 4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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