Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass quoted arguments to shell script and maintain quoting [duplicate]

Tags:

linux

bash

shell

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.


  • I tried "$1", but my quotes are thrown away. (Incorrect statement, read answer below)
  • I tried ""$1"" but my quotes are thrown away.
  • I tried to do '$1' but that's strong quoting so $1 never gets interpreted.
  • I realize I can do $@, but that gives me every param.
  • .... you get the picture

Any help would be appreciated!

like image 965
Ryan Griffith Avatar asked Nov 05 '15 22:11

Ryan Griffith


People also ask

How do you keep quotes in a Bash argument?

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.

How do you pass a double quote into a string in a shell script?

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: " ==> \", \ ==> \\

How do you use double quotes in double quotes in shell?

A double quote may be used within double quotes by preceding it with a backslash.

What is difference between $@ and $* in shell?

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.


1 Answers

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:

  • either: embed the quotes on invocation ./myscript.sh "\"My quoted Argument\""
  • or: embed the quotes inside myscript.sh: mailx -s "\"$1\""
like image 198
mklement0 Avatar answered Oct 03 '22 01:10

mklement0