Issue
I want my script to perform the product of all its integer arguments. Instead of performing a loop I tried to replace blanks with *
and then compute the operation. But I got the following result which I don't understand:
#!/bin/bash
# product.sh
echo $(( ${*// /*} )) # syntax error with ./product.sh 2 3 4
args=$*
echo $(( ${args// /*} )) # ./product.sh 2 3 4 => outputs 24
How is it that the first one produces an error while using an intermediate variable works fine?
Solution
How is it that the first one produces an error:
From the Bash Reference Manual:
If parameter is ‘@’ or ‘*’, the substitution operation is applied to each positional parameter in turn
(emphasis mine)
That is, the expression ${*// /*}
replaces spaces inside positional parameters, not the spaces separating positional parameters. That expression expands to 2 3 4
(which gives a syntax error when used in an arithmetic context), since the parameters itself don't contain a space. Try with
./product '2 ' '3 ' 4
and you will see the difference.
Answered By - M. Nejat Aydin Answer Checked By - Pedro (WPSolving Volunteer)