Wednesday, 15 August 2012

Bash: Control argument grouping in shell variables? -



Bash: Control argument grouping in shell variables? -

i have programme accepts argument of style -g "hello world".

for programme work correctly, -g , "hello world" have 2 separate arguments.

the shell script below thought automate something:

myprog=/path/to/bin myarg=-g\ \"hello\ world\" "$myprog" "$myarg"

of course, doesn't work because -g "hello world"is treated single argument bash.

one solution split -g , "hello world" straight in shell script have like:

myprog=/path/to/bin myarg1=-g myarg2=\"hello\ world\" "$myprog" "$myarg1" "$myarg2"

this work because 2 arguments treated such. however, because -g , "hello world" belong together, shell script kind of awkward. if there hundreds of arguments defined in script.

now question is, how can shell script treat 1 variable 2 arguments without splitting them 2 variables?

as @gniourf_gniourf said, best way handle array:

myprog=/path/to/bin myargs=(-g "hello world") "$myprog" "${myargs[@]}"

the assignment statement defines myargs array 2 elements: "-g" , "hello world". "${arrayname[@]" idiom tells shell treat each element of array separate argument, without word-splitting or otherwise mangling them.

bash shell command-line-arguments grouping argument-passing

No comments:

Post a Comment