Let's say I have a really simple shell script 'foo':
#!/bin/sh
echo $@
If I invoke it like so:
foo 1 2 3
It happily prints:
1 2 3
However, let's say one of my arguments is double-quote enclosed and contains whitespace:
foo 1 "this arg has whitespace" 3
foo happily prints:
1 this arg has whitespace 3
The double-quotes have been stripped! I know shell thinks its doing me a favor, but... I would like to get at the original version of the arguments, unmolested by shell's interpretation. Is there any way to do so?
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
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.
' 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).
In a shell, the most common way to escape special characters is to use a backslash before the characters. These special characters include characters like ?, +, $, !, and [. The other characters like ?, !, and $ have special meaning in the shell as well.
First, you probably want quoted version of $@
, i.e. "$@"
. To feel the difference, try putting more than one space inside the string.
Second, quotes are element of shell's syntax -- it doesn't do you a favor. To preserve them, you need to escape them. Examples:
foo 1 "\"this arg has whitespace\"" 3
foo 1 '"this arg has whitespace"' 3
Double quote $@:
#!/bin/sh
for ARG in "$@"
do
echo $ARG
done
Then:
foo 1 "this arg has whitespace" 3
will give you:
1
this arg has whitespace
3
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