tags:

views:

111

answers:

4

I have a bash script where I want to keep quotes in the arguments passed. Example:

./test.sh this is "some test"

then I want to use those arguments, and re-use them, including quotes and quotes around the whole argument list

I tried using \"$@\", but that removes the quotes inside the list.

How do I accomplish this ?

+4  A: 
./test.sh this is '"some test"'
yuku
A: 

Quotes are interpreted by bash and are not stored in command line arguments or variable values.

If you want to use quoted arguments, you have to quote them each time you use them:

val="$3"
echo "Hello World" > "$val"
mouviciel
+2  A: 

If it's safe to make the assumption that an argument that contains white space must have been (and should be) quoted, then you can add them like this:

#!/bin/bash
whitespace="[[:space:]]"
for i in "$@"
do
    if [[ $i =~ $whitespace ]]
    then
        i=\"$i\"
    fi
    echo "$i"
done

Here is a sample run:

$ ./argtest abc def "ghi jkl" $'mno\tpqr' $'stu\nvwx'
abc
def
"ghi jkl"
"mno    pqr"
"stu
vwx"

You can also insert tabs and newlines using Ctrl-V Tab and Ctrl-V Ctrl-J within double quotes instead of $'...'.

Dennis Williamson
A: 

using "$@" will substitute the arguments as a list, without re-splitting them on whitespace (they were split once when the shell script was invoked), which is generally exactly what you want if you just want to re-pass the arguments to another program.

What are you trying to do and in what way is it not working?

Chris Dodd