How to Use ls Command in Linux: Syntax and Examples
The
ls command in Linux lists files and directories in the current or specified location. You can use options like -l for detailed info or -a to show hidden files. Simply type ls followed by options or a path to see directory contents.Syntax
The basic syntax of the ls command is:
ls [options] [path]
Here, options modify the output (like showing details or hidden files), and path specifies the directory to list. If no path is given, it lists the current directory.
bash
ls [options] [path]
Example
This example shows how to list all files, including hidden ones, in long format with details like permissions, owner, size, and modification date.
bash
ls -la /etc
Output
total 1234
drwxr-xr-x 123 root root 12288 Apr 10 12:00 .
drwxr-xr-x 23 root root 4096 Apr 10 11:59 ..
-rw-r--r-- 1 root root 1234 Mar 5 09:00 hosts
-rw-r--r-- 1 root root 5678 Mar 5 09:00 passwd
... (more lines)
Common Pitfalls
One common mistake is forgetting that ls without options hides files starting with a dot (hidden files). Another is confusing the order of options and paths, which can cause errors or unexpected results.
Also, using ls on a non-existent directory will show an error.
bash
ls -l /nonexistent ls -l /etc
Output
ls: cannot access '/nonexistent': No such file or directory
Quick Reference
| Option | Description |
|---|---|
| -l | Show detailed list with permissions, owner, size, and date |
| -a | Include hidden files (those starting with a dot) |
| -h | Show file sizes in human-readable format (e.g., 1K, 2M) |
| -R | Recursively list subdirectories |
| -t | Sort by modification time, newest first |
| -r | Reverse the order of the sort |
Key Takeaways
Use
ls to list files and directories in Linux.Add
-l for detailed info and -a to see hidden files.Specify a path after options to list a different directory.
Order options before the path to avoid errors.
Check for typos to prevent 'No such file or directory' errors.