Learn ls Command in Unix with examples:
The Ls command is used to get a list of files and directories. Options can be used to get additional information about the files.
Know ls command syntax and options with practical examples and output.
ls Command in Unix with Examples
ls Syntax:
ls [options] [paths]
The ls command supports the following options:
- ls -a: list all files including hidden files. These are files that start with “.”.
- ls -A: list all files including hidden files except for “.” and “..” – these refer to the entries for the current directory, and for the parent directory.
- ls -R: list all files recursively, descending down the directory tree from the given path.
- ls -l: list the files in long format i.e. with an index number, owner name, group name, size, and permissions.
- ls – o: list the files in long format but without the group name.
- ls -g: list the files in long format but without the owner name.
- ls -i: list the files along with their index number.
- ls -s: list the files along with their size.
- ls -t: sort the list by time of modification, with the newest at the top.
- ls -S: sort the list by size, with the largest at the top.
- ls -r: reverse the sorting order.
Examples:
List all non-hidden files in the current directory
$ ls
E.g:
dir1 dir2 file1 file2
List all the files including hidden files in the current directory
$ ls -a
E.g:
.. ... .... .hfile dir1 dir2 file1 file2
List all the files including hidden files in the current directory
$ ls -al
E.g:
total 24 drwxr-xr-x 7 user staff 224 Jun 21 15:04 . drwxrwxrwx 18 user staff 576 Jun 21 15: 02. -rw-r--r-- 1 user staff 6 Jun 21 15:04 .hfile drwxr-xr-x 3 user staff 96 Jun 21 15:08 dir1 drwxr-xr-x 2 user staff 64 Jun 21 15:04 dir2 -rw-r--r-- 1 user staff 6 Jun 21 15:04 file1 -rw-r--r-- 1 user staff 4 Jun 21 15:08 file2
List all the files in the current directory in long format, sorted by modification time, oldest first
$ ls -lrt
E.g:
total 16 -rw-r--r-- 1 user staff 6 Jun 21 15:04 file1 drwxr-xr-x 2 user staff 64 Jun 21 15:04 dir2 -rw-r--r-- 1 user staff 4 Jun 21 15:08 file2 drwxr-xr-x 3 user staff 96 Jun 21 15:08 dir1
List all the files in the current directory in long format, sorted by size, smallest first
$ ls -lrS
E.g:
total 16 -rw-r--r-- 1 user staff 4 Jun 21 15:08 file2 -rw-r--r-- 1 user staff 6 Jun 21 15:04 file1 drwxr-xr-x 2 user staff 64 Jun 21 15:04 dir2 drwxr-xr-x 3 user staff 96 Jun 21 15:08 dir1
List all the files recursively from the current directory
$ ls -R
E.g:
dir1 dir2 file1 file2 ./dir1: file3 ./dir2:
Conclusion
In this tutorial, we discussed the various options that support the ls command. Hope this was helpful to learn the exact syntax and options for various ls commands in Unix.