Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force bash/zsh to evaluate 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 appears to be handing off the contents of $ARGS as a single argument to the executable. Here is a specific 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?

Note that when I put this type of command in a $!/bin/sh script, it performs as expected.

Thanks,

SetJmp

like image 883
Setjmp Avatar asked Sep 08 '11 21:09

Setjmp


People also ask

How do I pass multiple parameters in bash?

You can pass more than one argument to your bash script. In general, here is the syntax of passing multiple arguments to any bash script: script.sh arg1 arg2 arg3 … The second argument will be referenced by the $2 variable, the third argument is referenced by $3 , .. etc.

How do you assign a all the arguments to a single variable?

Assigning the arguments to a regular variable (as in args="$@" ) mashes all the arguments together like "$*" does. If you want to store the arguments in a variable, use an array with args=("$@") (the parentheses make it an array), and then reference them as e.g. "${args[0]}" etc.

How does bash handle command line arguments?

You can handle command-line arguments in a bash script in two ways. One is by using argument variables, and another is by using the getopts function.

Can a bash alias take argument?

Bash users need to understand that alias cannot take arguments and parameters. But we can use functions to take arguments and parameters while using alias commands.


2 Answers

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

like image 183
Tom Zych Avatar answered Sep 19 '22 05:09

Tom Zych


In zsh it's easy:

Use cmd ${=ARGS} to split $ARGS into separate arguments by word (split on whitespace).

Use cmd ${(f)ARGS} to split $ARGS into separate arguments by line (split on newlines but not spaces/tabs).

As others have mentioned, setting SH_WORD_SPLIT makes word splitting happen by default, but before you do that in zsh, cf. http://zsh.sourceforge.net/FAQ/zshfaq03.html for an explanation as to why whitespace splitting is not enabled by default.

like image 32
Michael Bosworth Avatar answered Sep 21 '22 05:09

Michael Bosworth