You tried to save output from the ls command with a redirect, but when you look at the resulting file, the format is not what you expected.
Use the -C
option on
ls when you redirect the output.
Here’s the ls command showing the contents of a directory:
$ ls a.out cong.txt def.conf file.txt more.txt zebra.list $
But when we save the output with the > to redirect it to a file, and then show the file contents, we get this:
$ ls > /tmp/save.out $ cat /tmp/save.out a.out cong.txt def.conf file.txt more.txt. zebra.list $
This time we’ll use the -C
option:
$ ls -C > /tmp/save.out $ cat /tmp/save.out a.out cong.txt def.conf file.txt more.txt zebra.list $
Alternatively, if we use the -1
option on ls when we don’t redirect, then
we get out-put like this:
$ ls -1 a.out Cong.txt def.conf. file.txt more.txt save.out zebra.list $
Then the original attempt at redirection matches this output.
Just when you thought that you understood redirection and you tried it on a simple ls command, it didn’t quite work right. What’s going on here?
The shell’s redirection is meant to be transparent to all programs, so programs don’t need special code to make their output redirect-able. The shell takes care of it when you use the > to send the output elsewhere. But it turns out that code can be added to a program to figure out when its output is being redirected. Then, the program can behave differently in those two cases—and that’s what ls is doing.
The authors of ls figured that if your output
is going to the screen then you probably want columnar output (-C
option), as screen real estate is limited.
But they assumed if you’re redirecting it to a file, then you’ll want
one file per line (the minus one -1
option) since there are more interesting things you can do (i.e., other
processing) that is easier if each filename is on a line by
itself.
18.223.195.29