The danger is not in solely running ls
. The danger is in typing or pasting its output. E.g. from an untrustworthy source you can get a file named &date;
. If you run some traditional ls
(or GNU ls -N
) then you will see
&date;
If you don't know what &
and ;
do in the shell then it will be easy for you to run one of these:
nano &date;
file &date;
rm &date;
cp &date; whatever
Any of these commands immediately runs date
. date
is not a harmful command, I deliberately chose a safe example. But what if the file is literally named funny story about `rm …`.txt
? Oh boy, let's see it! You may even be aware that a name with spaces requires quoting or escaping, there is a chance you choose double-quotes; and then:
less "funny story about `rm …`.txt"
In fact this exact command is almost always safe (it's safe, unless you have a file named …
you want to keep), but imagine this scenario with -rf ~
in place of …
. The inside of the backticks will be executed regardless if unquoted or double-quoted. To safely examine the file you should e.g. single-quote the name:
less 'funny story about `rm …`.txt'
The above command will not run rm
.
The documentation you linked to is about the feature of GNU ls
designed to protect naive users from this kind of mishaps. It explicitly states one of the reasons to change the default output is
Easier and safer cutting and pasting of filenames from/to the terminal
In the case of our example filenames GNU ls
will show you '&date;'
or 'funny story about `rm …`.txt'
. The point is if you type or paste exactly this after a command like file
or less
then you will quote right; maybe unwittingly, but right; even if you know nothing about how your shell interprets &
or backticks.
The feature is more sophisticated than "single-quote everything". Filenames themselves may contain single-quotes, so embracing mindlessly with single-quotes does not always work. In general GNU ls
may use backslashes, single-quotes, double-quotes, even ANSI-C quoting to show you filenames in safe forms you can paste*.
* Not all shells understand ANSI-C quoting, although if you're using GNU ls
then you're probably using a modern shell that does understand it (e.g. GNU bash
). Besides, it's not about creating snippets that in all circumstances work as expected when pasted; it's about avoiding snippets that work not as expected (or maybe rather "that work as expected by their rogue authors").
.
in your$PATH
(./ls
could be anything); and 2) Output ofls
is inconsistent, and cannot be parsed reliably, for use in pipelines, usestat
instead. – waltinator Sep 07 '23 at 22:55ls
but rather copy+paste of thels
output that's displayed on a terminal window, or piping thels
output to other programs to parse the contents. – Sotto Voce Sep 08 '23 at 06:05