Bash – Will ls Always List Files That rm Will Remove?

18.04bashhidden-fileslsrm

Something I feel I ought to know for sure: if I ls <something>, will rm <something> remove exactly the same files that ls displayed? Are there any circumstances where rm could remove files that ls did not show? (This is in the 18.04 bash)

Edit: thank you to everyone who answered. I think the full answer is a combination of all the answers, so I have accepted the most up-voted answer as "the answer".

Unexpected things I have learned along the way:

  • ls is not as straightforward as you might think in its handling of its arguments
  • In a simple un-fiddled-with installation of Ubuntu, .bashrc aliases ls
  • Don't name your files beginning with a dash as they can look like command arguments, and naming one -r is asking for it!

Best Answer

Well, both ls and rm operate on the arguments which are passed to them.

These arguments can be a simple file, so ls file.ext and rm file.ext operate on the same file and the outcome is clear (list the file / delete the file).

If instead argument is a directory, ls directory lists the content of the directory while rm directory won't work as is (i.e. rm without flags cannot remove directories, while if you do rm -r directory, it recursively deletes all files under directory and the directory itself).

But keep in mind that command line arguments can be subjected to shell expansion, so it's not always guaranteed that the same arguments are passed to both commands if they contain wildcards, variables, output from other commands, etc.

As an extreme example think ls $(rand).txt and rm $(rand).txt, the arguments are "the same" but the results are quite different!