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?
You need to quote the quotes:
or (more simply)
You need to quote the double quotes to make sure that the shell doesn't remove them when parsing word arguments.
What i'd do is to quote all the arguments received with spaces that might help your case.
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:
Double quote $@:
Then:
will give you:
Let's suppose you are in a more rigid set-up and you CANNOT change your command line, and make it more "friendly" by escaping the double quotes. For example:
First consider that inside your script you can't tell if an argument is passed with or without quotes, because the shell strips them.
So what you can possibly do is rebuilding double quotes for arguments containing whitespaces
This example rebuilds the whole command line, double-quoting arguments that have white spaces
Note this limitation. If you run this example
you will get this output
Note the last argument: since it had no spaces, it has not been enclosed again in double quotes, but this shouldn't be an issue.