user2249516 user2249516 - 1 month ago 9x
Linux Question

Bash pass variable as argument with quotes


is a program that just prints out the parameters;

$ ./program "Hello there"
Hello there

How can I properly pass arguments with quotes in from a variable? I am trying to do this;

$ args='"Hello there"'
$ echo ${args}
"Hello there"
$ ./program ${args}
Hello there # This is 1 argument

but instead, when I go through a variable the quotes in
seem to be ignored so I get;

$ args='"Hello there"'
$ echo ${args}
"Hello there"
$ ./program ${args}
"Hello there" # This is 2 arguments

Is it possible to have bash treat the quotes as if I entered them myself in the first code block?


I don't know where you got program from, but it appears that it's broken. Here's a correct way to write it in bash:


for arg in "$@"; do
    echo "$arg"

This will print each argument in a separate line to make them easier to distinguish (it will of course have a problem with arguments that contain a line break, but we will not pass such an argument).

After you have saved the above as program and gave it the execute permission, try this:

$ args='"Hello there"'
$ ./program "${args}"
"Hello there"


$ args='"Hello there"'
$ ./program ${args}