Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

replace

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?

like image 646
qouify Avatar asked Jun 04 '26 22:06

qouify


2 Answers

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.

like image 199
M. Nejat Aydin Avatar answered Jun 07 '26 13:06

M. Nejat Aydin


In your example, the value $* does not actually contain any literal spaces, so ${*// /*} does not do anything.

If it did, those asterisks would be subject to wildcard expansion, so the idea of performing a substitution would seem to be rather brittle even if it worked.

I would simply create a function to process the arguments, instead of rely on trickery with substitutions -- these tend to have icky corner cases when one of the arguments is a variable or etc.

mul () {
    case $# in
      [01]) echo "$@";;
      *) local n=$1; shift; echo $((n * $(mul "$@")));;
    esac
}
like image 37
tripleee Avatar answered Jun 07 '26 12:06

tripleee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!