Use find

To recursively list the contents of a directory including the path of each item, and display each item on a new line, it’s best to use the find command.

# List all items (including directories)
roast@planetroast:~/some-folder find .
.
./foo
./foo/file1
./foo/file2
./foo/bar
./foo/bar/file1
./foo/bar/file2
./foo/bar/file3

# List just the files
roast@planetroast:~/some-folder find . -type f
./foo/file1
./foo/file2
./foo/bar/file1
./foo/bar/file2
./foo/bar/file3

# List just the directories
roast@planetroast:~/some-folder find . -type d
.
./foo
./foo/bar

Sorting

If you need to order your list of files alphabetically you can pipe them into sort.

# Order the results by piping to sort
find . | sort

Why not use ls?

The ls command is probably the first thing you try when listing out files which seems logical because that’s its sole purpose right? Well yes, but things start to go pear shaped when you try to get a clean list because ls is designed to be read by humans.

Here we use ls with the -R option (to enable recursive listing) and the -1 option (to display each item on a new line). Sounds like it would work for us but the result looks like this:

# The problem with ls is that it is designed for humans
roast@planetroast:~/some-folder ls -R1
.:
bar
foo

./bar:
file1
file2
file3

./foo:
file1
file2

Even if you did edit the output of ls to use it in a script, there are some other reasons why it’s a bad idea relating to the types of filenames allowed in Unix systems. There’s a great blog post here explaining why you shouldn’t parse the output of ls.