Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a weird behaiour with ZSH when iterating over the content of a variable. A demo is better than a long talk in this case, so here is my problem:

(yoann@freya) test_bash » ls
file1  file2  file3
(yoann@freya) test_bash » for f in $(ls); do echo $f-SUF; done
file1-SUF
file2-SUF
file3-SUF
(yoann@freya) test_bash » files=$(ls); for f in $files; do echo $f-SUF; done 
file1
file2
file3-SUF
(yoann@freya) test_bash »

I expect the second iteration to have the same result as the first one. I have tried the following:

  • other people's ZSH (same distribution): worked fine
  • with bash on my machine: worked fine
  • remove my .zshrc: the problem persisted.
  • if I do

    files=$(ls); for f in $(echo $files | tr '\n' ' '); do echo $f-SUF; done

it works fine. But once again, if I capture the result of the echo piped on tr, I only get one -SUF at the end.

I am really out of ideas about what is happening, does anyone have a clue ?

Thanks.

Some information:

  • Distribution: debian Wheezy
  • zsh version: zsh 4.3.17 (x86_64-unknown-linux-gnu)

If it can be of any use:

(yoann@freya) test_bash » locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="en_US.utf8"
LC_NUMERIC="en_US.utf8"
LC_TIME="en_US.utf8"
LC_COLLATE="en_US.utf8"
LC_MONETARY="en_US.utf8"
LC_MESSAGES="en_US.utf8"
LC_PAPER="en_US.utf8"
LC_NAME="en_US.utf8"
LC_ADDRESS="en_US.utf8"
LC_TELEPHONE="en_US.utf8"
LC_MEASUREMENT="en_US.utf8"
LC_IDENTIFICATION="en_US.utf8"
LC_ALL=en_US.utf8
share|improve this question

1 Answer 1

up vote 1 down vote accepted

First, it is a bad idea to parse the output of ls. Instead use globbing (see section FILENAME GENERATION in man zshexpn), in your case

for f in *; do
  echo ${f}-SUP
done

The reason that both of your examples seem to work in bash (as long a there are no white spaces in your filenames etc.) is, that bash splits parameters on white spaces by default, which zsh does not do. You can get this behavior in zsh, too, with this option:

setopt SH_WORD_SPLIT

Explanation from man zshoptions

SH_WORD_SPLIT Causes field splitting to be performed on unquoted parameter expansions. Note that this option has nothing to do with word splitting. (See the section `Parameter Expansion'.)

But please take the advices given in the above link seriously!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.