Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a variable as if it were parameters?

Is there a way in Bash (without calling a 2nd script) to parse variables as if they were command line arguments? I'd like to be able to group them by quotes and such.

Example:

this="'hi there' name here"

for argument in $this; do
    echo "$argument"
done

which should print (but obviously doesn't)

hi there
name
here
like image 462
kiri Avatar asked Dec 03 '25 14:12

kiri


2 Answers

Don't store the arguments in a string. Arrays were invented for this purpose:

this=('hi there' name here)

for argument in "${this[@]}"; do
    echo "$argument"
done

It is highly recommended that you use this approach if you have control over this. If you don't, that is even more reason not to use eval, since unintended commands can be embedded in the value of this. For example:

$ this="'hi there'); echo gotcha; foo=("
$ eval args=($this)
gotcha

Less nefarious is something as simple as this="'hi there' *". eval will expand the * as a pattern, matching every file in the current directory.

like image 131
chepner Avatar answered Dec 06 '25 16:12

chepner


I worked out a half-answer myself. Consider the following code:

this="'hi there' name here"

eval args=($this)

for arg in "${args[@]}"; do
    echo "$arg"
done

which prints the desired output of

hi there
name
here
like image 44
kiri Avatar answered Dec 06 '25 17:12

kiri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!