I'm attempting to re-use parameters sent to my script as parameters for a command I execute within my script. See example below where I execute mailx
.
bash
$./myscript.sh "My quoted Argument"
myscript.sh
mailx -s $1
This ends up being executed as: mailx -s My Quoted Argument
.
"$1"
, but my quotes are thrown away. (Incorrect statement, read answer below)
""$1""
but my quotes are thrown away.'$1'
but that's strong quoting so $1 never gets interpreted. $@
, but that gives me every param.Any help would be appreciated!
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.
To quote a generic string with double quotes, perform the following actions: Add leading and trailing double quotes: aaa ==> "aaa" Escape with a backslash every double quote character and every backslash character: " ==> \", \ ==> \\
A double quote may be used within double quotes by preceding it with a backslash.
But if you put them inside quotes (which you should, as a general good practice), then $@ will pass your parameters as separate parameters, whereas $* will just pass all params as a single parameter.
mailx -s "$1"
correctly passes the value of $1
to mailx
as-is, embedded spaces and all.
In the case at hand, this means that My Quoted Argument
is passed as a single, literal argument to mailx
, which is probably your intent.
In a shell command line, quotes around string literals are syntactic elements demarcating argument boundaries that are removed by the shell in the process of parsing the command line (a process called quote removal).
If you really wanted to pass embedded double-quotes (which would be unusual), you have 2 options:
./myscript.sh "\"My quoted Argument\""
myscript.sh
: mailx -s "\"$1\""
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