Reputation: 691
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?
Upvotes: 0
Views: 436
Reputation: 126048
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.
Upvotes: 2