Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate string into shell arguments?

Tags:

shell

zsh

I have this test variable in ZSH:

test_str='echo "a \" b c"'

I'd like to parse this into an array of two strings ("echo" "a \" b c").

i.e. Read test_str as the shell itself would and give me back an array of arguments.

Please note that I'm not looking to split on white space or anything like that. This is really about parsing arbitrarily complex strings into shell arguments.

like image 231
event_jr Avatar asked Dec 11 '22 19:12

event_jr


1 Answers

Zsh has (z) modifier:

ARGS=( ${(z)test_str} )

. But this will produce echo and "a \" b c", it won’t unquote string. To unquote you have to use Q modifier:

ARGS=( ${(Q)${(z)test_str}} )

: results in having echo and a " b c in $ARGS array. Neither would execute code in or $(…), but (z) will split $(false true) into one argument.

that is to say:

% testfoo=${(z):-'blah $(false true)'}; echo $testfoo[2]
$(false true)
like image 83
ZyX Avatar answered Jan 04 '23 23:01

ZyX