Lull3rSkat3r
Lull3rSkat3r

Reputation: 118

Convert Environment Variable To Script Arguments

I am trying to provide a configuration layer to my users by allowing them to specify an environment variable with command line options. This config is actually for a wrapper program (run.sh) which receives the arguments and then invokes my program (program.sh).

I am having a problem with the arguments maintaining their quotations, which causes unexpected arguments to be passed through.

Here is an example implementation:

run.sh

exec `pwd`/program.sh ${CONFIG} "$@"

program.sh

for var in "$@"
do
    echo "$var"
done

An example invocation would look like this:

$> CONFIG='--foo="bar baz quo" --foo2="bar2 baz2"' ./run.sh hello abc123    
--foo="bar
baz
quo"
--foo2="bar2
baz2"
hello
abc123

I would have expected output like:

--foo="bar baz quo"
--foo2="bar2 baz2"
hello
abc123

I have tried wrapping ${CONFIG} in run.sh in qoutes, but that just makes a single argument of --foo="bar baz quo" --foo2="bar2 baz2". Escaping the quotations inside of CONFIG also yields an incorrect result.

Upvotes: 3

Views: 1527

Answers (1)

cdarke
cdarke

Reputation: 44354

run.sh

eval exec `pwd`/program.sh "${CONFIG}" "$@"

program.sh

for var                     # The 'in "$@"' is not required, it is the default
do
    echo "$var"
done

Output:

$ CONFIG='--foo="bar baz quo" --foo2="bar2 baz2"' ./run.sh hello 
--foo=bar baz quo
--foo2=bar2 baz2
hello

Note sure where the abc123 in your output is supposed to come from.

Upvotes: 3

Related Questions