Just pipe ls

I got a lot of flack on my last post for suggesting piping to ls a la:

ls | grep file

Why? Because a few things come together:

  • UNIX allows filenames to contain any character but NUL and / (you can even use emojis).

  • Bash uses space to delimits arguments and newline to delimit records.

  • ls dumps filenames separated by a space (when STDOUT is a terminal) or newline (when STDOUT is redirected).

Put it all together, and ls | grep can do weird things.

But. In practice, it’s fine.

Most file names don’t have spaces (maybe a rogue album title or download) and almost none have newlines.

And if you’re unlucky enough to have them, use detox to fix the names.

If you’re in the rare 0.000001% that you have weird file names and you can’t modify the names (or you’re writing a tool for the 0.00001%). Okay, fine. You can’t pipe ls. Use find -print0 | grep -z.

For the rest of you, just use ls. It’ll be fine.