I am reading about the pitfalls of parsing ls and the examples given are about looping ls with for/while. The article title says 'parsing ls' - does that mean piping the output of ls to awk and other programs is just as bad?

ls /my/path/ | awk '{print $NF}'

When piping output of ls to other programs, is it better to loop a glob instead?

for p in /my/path/*; do
    echo "$p" | awk '{print $NF}'

I assume since ls can potentially output newlines etc piping ls directly to other programs is also 'a bad practice' but I don't see much information in that respect.

  • It does and so does the link you provided. – Jesse_b Nov 16 at 13:54

While looping a glob is safer than piping the output of ls, keep in mind that the output of ls is only as dangerous as you make it. If you are the sole user of the system, and you are sensible about naming your files, then piping ls is not a big deal. As your article mentions, it is really only when you start putting odd characters (newlines, pipes, etc) into your file names that these issues arise. I would really only be concerned about safely piping ls when using a system that is shared among a large group of people or has files randomly generated by some program. For just general use on a private computer, sensible file naming is probably simpler than writing a loop.

  • It’s as dangerous as the programs you run make it. Do you know absolutely everything that every single program you run does? – Stephen Kitt Nov 16 at 8:54

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