How to make bash / zsh evaluate a parameter as multiple arguments when applied to a command

I am trying to run a program like this:

$CMD $ARGS 

where $ ARGS is a set of arguments with spaces. However, zsh seems to pass the contents of $ ARGS as the only argument to the executable. Here is a concrete example:

 $export ARGS="localhost -p22" $ssh $ARGS ssh: Could not resolve hostname localhost -p22: Name or service not known 

Is there a bash or zsh flag that controls this behavior?

Please note that when I put this type of command in the $! / Bin / sh script, it executes as expected.

Thanks,

Setjmp

+6
source share
3 answers

It will work if you use eval $CMD $ARGS .

+4
source

If you want the string variable (as well as arrays) to be divided into words before passing the command, use $=VAR . There is also an option ( shwordsplit , if I'm not mistaken) that will make any command $VAR act like command $=VAR , but I suggest not setting it: Iโ€™m really uncomfortable entering things like command "$VAR" (zsh: command $VAR ) and command "${ARRAY[@]}" (zsh: command $ARRAY ).

+7
source

In zsh, this is easy:

Use cmd ${=ARGS} to separate $ARGS into separate arguments by a word (space division).

Use cmd ${(f)ARGS} to split $ARGS into separate arguments per line (newline, but not spaces / tabs).

As others noted, setting SH_WORD_SPLIT does the default word separation, but before you do it in zsh, cf. http://zsh.sourceforge.net/FAQ/zshfaq03.html for an explanation of why space separation is not enabled by default.

+5
source

Source: https://habr.com/ru/post/896928/


All Articles