Why does the redirection symbol change the behavior of ls?
bash, linux, unix
Solution
`ls` tests its output stream to see whether it is a terminal, and it modifies its behavior depending on that.
This is documented; the `man` page for `ls` documents several things that depend on whether the output is a terminal:
- If the output is a terminal, `-C` (for multi-column output) is a default, otherwise `-1` (one-column) is a default.
- If `-l` or `-s` is used and the output is a terminal, a sum for all file sizes or blocks, respectively, is printed on a line before the listing.
- If the output is a terminal, `-q` is a default. This prints non-graphic characters as “?”. Otherwise, `-v` and `-w` are defaults. I am a bit unclear on the difference between `-v` and `-w`. The documentation I have says `-v` forces “unedited printing of non-graphic characters” and `-w` forces “raw printing of non-printable characters.”
Problem
So, I have always had doubts about how redirection works in the following situations: I type "ls" and all the filenames are separated by white spaces: ``` test$ touch a b c test$ ls a b c ``` I use a ">" to redirect STDOUT to a file: ``` test$ ls > ls.txt test$ cat ls.txt a b c ls.txt ``` It is interesting to see that the format changes, with the filenames separated by newline characters. It seems that the output is generated by `ls -1`. Why is the output in the latter case different from that in the former case? Can ls actually see the ">" symbol so it changes its behavior?