Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve double quotes in $@ in a shell script?

Tags:

shell

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?

like image 362
Stephen Gross Avatar asked Sep 20 '10 21:09

Stephen Gross


People also ask

What is $@ in bash script?

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.

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 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).

How do you handle special characters in Unix shell script?

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.


2 Answers

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
like image 148
Roman Cheplyaka Avatar answered Oct 27 '22 08:10

Roman Cheplyaka


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
like image 32
Alex Howansky Avatar answered Oct 27 '22 09:10

Alex Howansky