Search code examples
iterationzshlines

How do I iterate over all the lines output by a command in zsh?


How do I iterate over all the lines output by a command using zsh, without setting IFS?

The reason is that I want to run a command against every file output by a command, and some of these files contain spaces.

Eg, given the deleted file:

foo/bar baz/gamma

That is, a single directory 'foo', containing a sub directory 'bar baz', containing a file 'gamma'.

Then running:

git ls-files --deleted | xargs ls

Will report in that file being handled as two files: 'foo/bar', and '/baz/gamma'.

I need it to handle it as one file: 'foo/bar baz/gamma'.


Solution

  • Using tr and the -0 option of xargs, assuming that the lines don't contain \000 (NUL), which is a fair assumption due to NUL being one of the characters that can't appear in filenames:

    git ls-files --deleted | tr '\n' '\000' | xargs -0 ls
    

    this turns the line: foo/bar baz/gamma\n into foo/bar baz/gamma\000 which xargs -0 knows how to handle