user2249516 user2249516 - 2 months ago 17
Linux Question

Bash pass variable as argument with quotes

Assume

./program
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
args
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?

Answer

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:

#!/bin/bash

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

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"

whereas

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