Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unpack string in variable

Tags:

variables

zsh

In Bash, I can use the following code:

[ "$sshcmd" = "" ] && sshcmd="ssh -someopts myhost"

$sshcmd "echo hello world"

In ZSH, the same code does not work because it tries to find a "ssh -someopts myhost" executable. How can I do the same thing in ZSH?

Thanks, Albert

like image 924
Albert Avatar asked Nov 05 '22 10:11

Albert


1 Answers

To split a string at whitespace (more generally, at $IFS) like other shells: $=sshcmd

But you should instead make sshcmd an array, so that your commands still works if one of the options contains whitespace:

sshcmd=(ssh -someopts myopts)
$sshcmd[@] "echo hello world"

This applies to bash and ksh too, by the way; but there you must also protect the array variable substitution against further splitting and filename expansion:

sshcmd=(ssh -someopts myopts)
"${sshcmd[@]}" "echo hello world"
like image 144
Gilles 'SO- stop being evil' Avatar answered Nov 15 '22 20:11

Gilles 'SO- stop being evil'