Saving Output from the ls Command

Problem

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.

Solution

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.

Discussion

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 ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.