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

Re: somehow offtopic: looping filenames



Stephen Blott wrote:
[...]
> ls | tr '\n' '\0' | xargs -0 -n 1 flac --

This is a pet peeve of mine, so I need to chime in...

Using ls for generating file lists is always wrong. And always, there is
a more robust way of dealing with the problem at hand using either shell
globing or `find(1)'. (I used to have two "almost"s in that paragraph,
but leaving them in would really overstate the relevance of possible
situations¹.)

There is nothing about this, that would improve the behaviour of a
simple for loop like

  for i in *; flac -- $i

(That's `short_loops' syntax, which is on by default in zsh. And it
relies on `sh_word_split' being unset, which is also the default
behaviour in zsh.)

Worse, it's *less* robust, because it's treating newline characters
specially, although they are perfectly legal characters in a file name
(albeit not very common ones). Also, if the user has an alias in place,
like say,

  alias ls='ls -F'

...that is not going to work either, because that will cause ls to
append a / to directory names, a * to executable files and so on.


I know there are HOWTOs and tutorials online, that advocate constructs
like that. And even worse ones, like "for i in `ls`; do...". But that
doesn't make them good examples of shell programming.


I don't mean to offend with this reply. And I hope that my point is
making sense to you. I've written about this in the past² (but it's in
German) and so has the guy who maintains the FAQ for #bash (the IRC
channel for GNU bash on freenode)³. Refer that that for more details on
parsing the output from `ls'.


Regards, Frank

¹ There was one time, when someone asked me: Okay so "for i in `ls`" is
  bad, but what about when I want the generated list to be sorted by
  some criteria (like by modification time instead of the usual
  alphabetic order). And that's indeed not that easy with POSIX shell.
  In zsh, however, there are glob qualifiers like (O.) and (o.)
  (where`.' is a character that specifies a property to sort by), which
  allow the user to sort the result of a glob to his/her requirements.
  So that point is moot as well, if we're talking about zsh.

² <http://bewatermyfriend.org/posts/2007/02-08.12-18-45-rants.html>
³ <http://mywiki.wooledge.org/ParsingLs>



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