If you want a variable that expands to more than one argument use an array:
var=(ls -l)
$var
But to store code, the most obvious storage type is a function:
myfunction() ls -l
Or:
myfunction() ls -l "$@"
for that function to take extra arguments to be passed to ls
.
The fact that bash
like most other Bourne-like shells splits unquoted variables upon expansion is IMO a bug. See the kind of problems it leads to. But if you want that behaviour, you can set the shwordsplit
option. You could also add the globsubst
option to restore another bug found in bash
and other Bourne-like shells where variable expansion is also subject to globbing (aka pathname expansion). Or do the full shebang with emulate sh
or emulate ksh
(but lose a few more zsh features).
Without having to go there, you can also tell zsh
to explicitly split a variable:
var='ls -l'
$=var # split on $IFS like the $var of bash/sh
${(s[ ])var} # split on spaces only regardless of the value of $IFS
var='*.txt'
echo $~var # do pathname expansion like the $var of bash/sh
var='ls -ld -- *.txt'
$=~var # do both word splitting and filename generation
bash
. while it's close enough, it's still different :)