The ls command is one of the most used commands in Linux. In this article, I go over the absolute basics you need to know to be able to use it effectively.
The ls command can be used to
- List the contents of a directory
- Show information about a file or directory
If the ls command is used without specifying a directory or file name, it’ll list the contents of the current working directory. This is the most basic use of the command.
If it’s used with a directory name, then it’ll list the contents of that directory.
If it’s used with a file name, then it’ll show information about that file.
ls -l /etc/passwd
If I wanna see the info about a directory (rather than its contents) I can use the -d flag.
ls -ld /var/log/
This flag is for long format list. it shows information about the permissions, links, owner user and group, size and last modified time (last time file’s content has changed).
This flag includes the hidden files (dotfiles) in the output.
By default, the size shown in the ls command is in bytes, which can be hard to read for larger files. This flag shows the sizes in a human-readable form.
This flag lists the contents of the subdirectories under the target directory recursively.
By default, the ls command sorts the output alphabetically. These flags can be used to change the sorting:
This flag (capital S) sorts the output based on size (largest first).
This flag sorts the output based on time modified (most recently modified first).
Reverses the order of sorting. For instance, if I want to see the smallest file first, I can use:
Running the ls Command on Multiple Files
You can run the ls command on multiple files or directories at once. To do that, you just gotta write the name of those files or directories after the ls command one after the other.
For instance to see the information about file1 and file2 that exist in the current directory you can run:
ls -l file1 file2
A more useful use case is to use file globbing to see the information of all the files that match a specific criteria. For instance, if you wanna run ls on all the HTML files in the current directory, you can run:
ls -l *.html
In this article, I went over the basics of the ls command and its most useful flags. If you need to know more about it you can always use the man page