7

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!

Ryan Griffith
  • 1,591
  • 17
  • 41

3 Answers3

8

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\""
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    Thanks @mklement0. Somehow in my testing, I must have overlooked quoting the argument in my script when passing it to `mailx`. – Ryan Griffith Nov 05 '15 at 23:21
-1

Can you try passing the argument like this

$./myscript.sh \"My quoted Argument\"?
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
Carlos
  • 1,340
  • 1
  • 10
  • 26
  • 1
    I would like to be able to pass arguments as I would to any normal command without having to understand the inner workings of that command. I.e. I do not want to modify how I pass parameters because of a shortcoming of the scripts design. – Ryan Griffith Nov 05 '15 at 23:01
-1

You may just put escaped quotes around $1 in your script

mailx -s \"$1\"
Paolo
  • 15,233
  • 27
  • 70
  • 91