tags:

views:

22

answers:

1

Hi,

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

A: 

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"
Gilles
I am getting this via an environment from Bash, so I think an array is not an option (or how can I automatically convert it?). But `$=sshcmd` works, thanks!
Albert
@Albert To split something just like the shell does, use `${(z)sshcmd}`. It will handle the case when sshcmd contains quoted parameters: if sshcmd contains a string `a 'b c d'`, `$=sshcmd` will split it into `a`, `'b`, `c`, `d'`, while `${(z)sshcmd}` into `a`, `'b c d'`. It also handles `$(...)`, `"..."`, etc; see PARAMETER EXPANSION section in man zshexpn.
ZyX
Thanks @ZyX, this seems much more useful!
Albert
@Albert: If in bash you'd use `$sshcmd`, then the zsh equivalent is `$=sshcmd`; you just can't have whitespace in options then, as the information of whether a space is a separator or part of the option has been lost. If in bash you'd use `eval $sshcmd`, then zsh comes close (but with saner quoting requirements) with `${(z)sshcmd}`; though zsh would be even more compatible with `(emulate sh; eval $sshcmd)`.
Gilles