0

I have been told that it is unwise to parse the output of LS due to security precautions.

The adage used was "parse sparsely and dont eat parsley"

I was attempting to count the amount of files within a directory by using

ls -la | wc -l  

I was told to never, never do this but I cant grasp why.

I was told one reason is because a file name could be shuffled into another command by accident. For example, if a file was within the directory named '-l'.

I was also told about using '--', for example ls -la --. If I understand correctly this is supposed to tell bash where to signal the end of commands but even if you used this you still shouldn't parse the output of ls.

Why ?

Oscalation
  • 1,139
  • If it's only counting you can do it safely with ls -qa | wc -l but then, there are better ways to count items in a directory. – don_crissti Oct 18 '17 at 20:23
  • the problem with "why not parse LS" is the answers are so complicated I cant get anything out of them – Oscalation Oct 18 '17 at 20:28
  • Don can you share the better way to count items in a directory? I'm assuming its with the find command? – Oscalation Oct 18 '17 at 20:29
  • Search the site for "count files in a directory"... – don_crissti Oct 18 '17 at 20:31
  • 1
    The Bash Wooledge page on it is a bit more clear. And Why is looping over find's output bad practice? is fairly relevant, also. Hope that helps. – Wildcard Oct 18 '17 at 20:32
  • Also, the comments on the other question are much clearer than the answers. To quote one of these: "You have a stream of text produced by ls that can contain any bytes except the null byte or the slash. There is fundamentally no way to recover that into a list of filenames. The transformation ls does is non-reversible, even if it doesn't replace any nonprintable characters. When it replaces non-printable characters, you're in an even worse situation." – Wildcard Oct 18 '17 at 20:39
  • Thank you. The "why not parse ls" post has a comment that says basically the answer is too complicated and it has 46 upvotes. I added my vote there also. I will read these links you provided. – Oscalation Oct 18 '17 at 20:39

0 Answers0