Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: for loop with parameter expansion in zsh vs. bash



2015-11-03 08:47:42 +0100, Alexander Skwar:
[...]
> > IFS=:
> > for e in $~PATH

Sorry, meant $=PATH above ($= looks like scissors)

> > Or use the "s" expansion flag:
> >
> > for e in "${(s(:))PATH}"

Note that those don't work if $PATH is empty (which for command
search means one empty element) or unset (which for command
search means commands are looked in a default $PATH (whose value
depends on the shell)).

> ​Great. Thanks. Appreciated.
> 
> 
> Too bad, that there's such a difference between the shells. Makes it hard
> to share snippets with co-workers, who (for reasons, that I fail to
> understand) don't use zsh.
> 
> Because of that, I'm actually using something along the lines of:
> 
>   for e in $(echo "$PATH" | tr ':' ' '); do echo e $e; done
> 
> This works everywhere.​

Note that it is slightly more correct in zsh (that performs only
split upon command substitution) than in other shells that
perform split+glob. The use of echo causes problems with things
that start with - or contain backslashes though. The use of
command substitution means that trailing newlines in the last
element are trimmed.

set -o noglob; IFS=:; for e in $(printf %s "$PATH")

would be better (still a problem for trailing newlines).

Note that if you want to have zsh interpret sh code, you can use
"emulate -L zsh". The -L makes that "emulation" local to the
current function context.

So to share code between zsh and POSIX compliant shells, you
could do:

if [ "$ZSH_VERSION" ]; then
  alias 'START_SH_CODE=function { emulate -L sh'
  alias 'END_SH_CODE=} "$@"'
else
  START_SH_CODE() { :; }
  END_SH_CODE() { :; }
fi

And use as:

START_SH_CODE
IFS=:
set -f
for e in $PATH; do ...; done
END_SH_CODE

(note that it has the side effect of creating a function context
(the code is parsed as a whole, the positional parameters and
variables you declare inside are local to that block, "return"
breaks only out of that block.

(note that doing the same for bash (which by default, unless in
sh emulation is not POSIX compliant either though the
differences are a lot smaller) is a lot trickier as bash doesn't
have local scope for options or anonymous functions like zsh).

-- 
Stephane



Messages sorted by: Reverse Date, Date, Thread, Author