Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does'nt ${*// /*} work to replace blanks with * in command line arguments?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading