0

I have a program that accepts an argument of the style -g "hello world".

For the program to work correctly, -g and "hello world" actually have to be two separate arguments.

The shell script below is thought to automate something:

MYPROG=/path/to/bin
MYARG=-g\ \"hello\ world\"

"$MYPROG" "$MYARG"

Of course, this doesn't work because -g "hello world"is treated as a single argument by bash.

One solution would be to split -g and "hello world" directly in the shell script to have something like:

MYPROG=/path/to/bin
MYARG1=-g
MYARG2=\"hello\ world\"

"$MYPROG" "$MYARG1" "$MYARG2"

This would work because now the two arguments are treated as such. However, because -g and "hello world" belong together, the shell script would look kind of awkward. Especially if there are hundreds of arguments defined like this in the script.

Now my question is, how can I get my shell script to treat the one variable as two arguments without splitting them into two variables?

2
  • 2
    The only sensible way to deal with this (in Bash) is to use an array. Commented Oct 18, 2014 at 19:59
  • @shellter I already tried that, unfortunately it doesn't group my args at a whitespace. Commented Oct 19, 2014 at 8:33

1 Answer 1

2

As @gniourf_gniourf said, the best way to handle this is with an array:

MYPROG=/path/to/bin
MYARGS=(-g "hello world")

"$MYPROG" "${MYARGS[@]}"

The assignment statement defines MYARGS as an array with two elements: "-g" and "hello world". The "${arrayname[@]" idiom tells the shell to treat each element of the array as a separate argument, without word-splitting or otherwise mangling them.

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

1 Comment

Thank you both, this does what I want without unnecessarily complicating my shell script!

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.