The ls command

list directory contents 37 examples from the lessons of the IVski Linux Playground — try them in the terminal next to them.

Options in the examples

-l
use a long listing format
-a, --all
do not ignore entries starting with .
-h, --human-readable
with -l and -s, print sizes like 1K 234M 2G etc.
-t
sort by time, newest first; see --time
-S
sort by file size, largest first
-d, --directory
list directories themselves, not their contents
-R, --recursive
list subdirectories recursively
-r, --reverse
reverse order while sorting

Examples

ls --help
ls
ls -l

Long format (permissions, size, date)

ls -a

Show hidden files (starting with .)

ls -la

Both combined

ls -lh

Human-readable file sizes (KB, MB)

ls -lt

Sort by modification time

ls -lr

Reverse order

ls -R

Recursive (show subdirectories)

ls /etc
ls /var/log
ls ~/documents
ls *.txt

See what files match

ls /etc | wc -l

How many files in /etc?

ls -la file.txt
ls -la | grep '.txt'

List only .txt files

ls -la | sort -k5 -n

Sort by file size

ls -lhS
ls /exists

Returns 0 (success)

ls /notexist

Returns 2 (error)

ls -l /var/www/html
ls -l /etc/nginx/sites-enabled
ls -t ~/backups/docs-*.tar.gz

Newest first

ls -t ~/backups/docs-*.tar.gz | tail -n +4

Everything after the 3rd line: the old ones

ls -t ~/backups/docs-*.tar.gz | tail -n +4 | xargs -r rm

…deleted (-r: not when there are none)

ls -laS /var/log

Largest files in a directory, sorted

ls -lh backup-*.tar.gz
ls -l ~/scripts/backup.sh

Can the script actually be executed?

ls -lh ~/backups

Did the backup file appear?

ls -l /var/log/app

Who can read these files?

ls -lh /backups

Which backups exist, and how fresh are they?

ls -la ~/projects/website

Check what came back

ls -l /etc/resolv.conf*

Is there a known-good copy?

ls -la ~/.ssh

Who may read and write your SSH files?

ls -l /etc/worker/

Who owns the config, who may read it?

ls -l /var/www/gallery

Who owns the files? Who may read them?

ls -ld /var/www/gallery/photos

The folder itself (-d)

Lessons that use ls

Related commands