I tried building a set of arguments in a variable and passing that to a script but the behavior different from what I expected.
test.sh
#!/bin/bash
for var in "$@"; do
echo "$var"
done
input
usr@host$ ARGS="-a \"arg one\" -b \"arg two\""
usr@host$ ./test.sh $ARGS
output
-a
"arg
one"
-b
"arg
two"
expected
-a
arg one
-b
arg two
Note if you pass the quoted arguments directly to the script it works. I also can work around this with eval but I wanted to understand why the first approach failed.
workaround
ARGS="./test.sh -a "arg one" -b "arg two""
eval $ARGS
' appearing in double quotes is escaped using a backslash. The backslash preceding the ' ! ' is not removed. The special parameters ' * ' and ' @ ' have special meaning when in double quotes (see Shell Parameter Expansion).
When you want to pass all the arguments to another script, or function, use "$@" (without escaping your quotes). See this answer: Difference between single and double quotes in Bash.
COMMAND "$variable2" "$variable2" "$variable2" # Executes COMMAND with 3 empty arguments. COMMAND "$variable2 $variable2 $variable2" # Executes COMMAND with 1 argument (2 spaces). # Thanks, Stéphane Chazelas. In the above you can see that depending on how you quote the variable it's either no arguments, 3, or 1.
To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 … To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 …
You should use an array, which in some sense provides a 2nd level of quoting:
ARGS=(-a "arg one" -b "arg two")
./test.sh "${ARGS[@]}"
The array expansion produces one word per element of the array, so that the whitespace you quoted when the array was created is not treated as a word separator when constructing the list of arguments that are passed to test.sh
.
Note that arrays are not supported by the POSIX shell, but this is the precise shortcoming in the POSIX shell that arrays were introduced to correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With