Will ls always list the files that rm will remove?

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!


If you're thinking of something like ls foo*.txt vs. rm foo*.txt, then yes, they will show and remove the same files. The shell expands the glob, and passes it to the command in question, and the commands work on the listed files. One listing them, one removing them.

The obvious difference is that if any of those files happened to be a directory, then ls would list its contents, but rm would fail to remove it. That's usually not a problem, since rm would remove less than what was shown by ls.

The big issue here comes from running ls * or rm * in a directory containing filenames starting with a dash. They would expand to the command lines of the two programs as if you wrote them out yourself, and ls would take -r to mean "reverse sort order", while rm would take -r to mean a recursive removal. The difference matters if you have subdirectories at least two levels deep. (ls * will show the contents of the first level directories, but rm -r * will everything past the first sublevel, too.)

To avoid that, write permissive globs with a leading ./ to indicate the current directory, and/or put a -- to signal the end of option processing before the glob (i.e. rm ./* or rm -- *).

With a glob like *.txt, that's actually not an issue since the dot is an invalid option character, and will cause an error (until someone expands the utilities to invent a meaning for it), but it's still safer to put the ./ there anyway.


Of course you could also get different results for the two commands if you changed the shell's globbing options, or created/moved/removed files in between the commands, but I doubt you meant any of those cases. (Dealing with new/moved files would be extremely messy to do safely.)