3

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.

4
  • Where does the abc123 come from? Commented Mar 28, 2016 at 16:50
  • The environment is not the right way to pass arguments like this. Commented Mar 28, 2016 at 17:04
  • @cdarke the abc123 got put on the wrong line, updating the question to reflect that. Commented Mar 28, 2016 at 17:20
  • 1
    You can't do this safely. This is a problem with system init scripts as well and has been for ages. The only way to pass space-safe arguments is with an array which you can't export but could pass by name in some contexts. Commented Mar 28, 2016 at 18:44

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is risky as CONFIG variable is coming from external users. Once can set CONFIG='$(rm program.sh); --foo="bar baz quo" --foo2="bar2 baz2"'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.