1. Overview

Listing files under a directory is probably one of the most common operations when we work under the Linux command line.

Sometimes, we would like to get the list of files in a particular format — for example, one file per line.

In this quick tutorial, we’ll see how to achieve that.

2. Using the ls Command and the -1 Option

When we want to list files in a directory, the ls command could be the first command that we can think of. However, if we run the command without any options, the ls command will output filenames in a single line. An example will explain it clearly:

$ ls
aDir  file1.txt  file2.txt  file3.txt

Of course, we know that the commonly used -l option can make ls print each filename in one line. That’s true. However, other information, such as permissions and the owner of the file, will appear in the output together with the filename:

$ ls -l
total 0
drwxr-xr-x 2 kent kent 40 Sep 30 21:07 aDir
-rw-r--r-- 1 kent kent  0 Sep 30 21:07 file1.txt
-rw-r--r-- 1 kent kent  0 Sep 30 21:07 file2.txt
-rw-r--r-- 1 kent kent  0 Sep 30 21:07 file3.txt

If we would like to see only filenames and one file per line, we can execute the ls command with the -1 option:

$ ls -1
aDir
file1.txt
file2.txt
file3.txt

If we want to show hidden files (also known as dot-files ), we can add the -a option to the command above:

$ ls -1a
.
..
aDir
file1.txt
file2.txt
file3.txt
.hidden

3. Choosing the ls Output Target Other Than a Terminal

We’ve learned that the ls command without any option will print filenames in one single line:

$ ls -a
.  ..  aDir  file1.txt  file2.txt  foo  .hidden

Also, we know if we pipe some output to the cat command, it’ll print the output as it is:

$ echo "This is a beautiful string." | cat
This is a beautiful string.

Now, let’s pipe the result of the ls command to the cat command and see what will come out:

$ ls -a | cat
.
..
aDir
file1.txt
file2.txt
file3.txt
.hidden

As we can see in the output above, each filename sits in a line magically.

This is because the ls command adjusts the output according to the output targets, such as a terminal, a redirection, or a pipe.

If the output target is not a terminal, the -1 option will be the default option of the ls command. Thus, ls will output one filename per line to the target.

We’ve addressed that when the output target is a pipe, the ls command will output a file per line.

Next, let’s see another example when ls outputs to a redirection:

$ ls -a > /tmp/ls.output

$ cat /tmp/ls.output
.
..
aDir
file1.txt
file2.txt
file3.txt
.hidden

As the example shows, ls outputs a file per line when the target is a file redirection.

4. Conclusion

In this quick tutorial, we’ve addressed how to use the ls command to list one file per line. The -1 option is the key.

Further, we’ve learned that the ls command will adjust its output depending on the different output targets.