Search code examples
bashquotes

How can I keep quotes in Bash arguments?


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 reuse 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?


Solution

  • Just use single quotes around the string with the double quotes:

    ./test.sh this is '"some test"'
    

    So the double quotes of inside the single quotes were also interpreted as string.

    But I would recommend to put the whole string between single quotes:

     ./test.sh 'this is "some test" '
    

    In order to understand what the shell is doing or rather interpreting arguments in scripts, you can write a little script like this:

    #!/bin/bash
    
    echo $@
    echo "$@"
    

    Then you'll see and test, what's going on when calling a script with different strings