ls — List Directory Contents¶
Quick Start / TL;DR Cheat Sheet
ls— Show files in current folderls -l -h— Detailed list with human-readable file sizes (e.g. 5MB, 1.2GB)ls -a— Show all files including hidden files (files starting with.)ls -l -t— Sort files by modified date (newest files at the top)ls -l -S -h— Sort files by size (largest files at the top)
Overview¶
The ls command is used to list files and folders. Think of it as opening a folder in File Explorer or Finder, but in your terminal.
Syntax¶
If no FILE is given, the current directory (.) is listed.
Options Reference¶
Display Options¶
| Option | Long Form | Description |
|---|---|---|
-l | --format=long | Long listing format (permissions, owner, size, date) |
-a | --all | Show hidden files (starting with .) |
-A | --almost-all | Show hidden files, but not . and .. |
-h | --human-readable | Human-readable sizes (KB, MB, GB) — use with -l |
-s | --size | Print allocated block size of each file |
-i | --inode | Print the inode number |
-d | --directory | List directory itself, not its contents |
-R | --recursive | List subdirectories recursively |
-1 | One file per line |
Sorting Options¶
| Option | Description |
|---|---|
-t | Sort by modification time (newest first) |
-S | Sort by file size (largest first) |
-X | Sort by file extension |
-r | Reverse the sort order |
-U | Do not sort — list in directory order (fastest) |
--sort=none | Same as -U |
Color & Format Options¶
| Option | Description |
|---|---|
--color=auto | Colorize output when writing to a terminal |
-F / --classify | Append type indicator (/ dir, * exec, @ symlink, = socket) |
-p | Append / to directory names |
-Q | Quote file names with double quotes |
--group-directories-first | List directories before files |
Examples¶
Basic Usage¶
# List current directory
ls
# List a specific path
ls /var/log
# List multiple paths
ls /etc /usr /var
Long Listing¶
Output breakdown:
| Field | Value | Meaning |
|---|---|---|
| File type | - | Regular file (d=dir, l=link, b=block, c=char, p=pipe, s=socket) |
| Permissions | rw-r--r-- | Owner: read+write, Group: read, Others: read |
| Hard links | 1 | Number of hard links to this inode |
| Owner | root | File owner username |
| Group | root | Owning group |
| Size | 2847 | Size in bytes (use -h for human-readable) |
| Timestamp | Jan 15 09:22 | Last modification time (mtime) |
| Name | /etc/passwd | Filename or path |
Show Hidden Files¶
total 96
drwxr-xr-x 8 pruthvi pruthvi 4096 Jan 15 10:00 .
drwxr-xr-x 12 root root 4096 Jan 10 08:00 ..
-rw------- 1 pruthvi pruthvi 2048 Jan 15 09:55 .bash_history
-rw-r--r-- 1 pruthvi pruthvi 220 Jan 10 08:00 .bash_logout
-rw-r--r-- 1 pruthvi pruthvi 3526 Jan 10 08:00 .bashrc
drwxr-xr-x 4 pruthvi pruthvi 4096 Jan 12 14:00 .config
-rw-r--r-- 1 pruthvi pruthvi 807 Jan 10 08:00 .profile
Sort by Time (Newest First)¶
Human-Readable Sizes¶
Show Inode Numbers¶
1048578 -rw-r--r-- 1 root root 2847 Jan 15 09:22 /etc/passwd
1048579 -rw-r----- 1 root shadow 1423 Jan 15 09:22 /etc/shadow
Inodes
An inode number uniquely identifies a file within a filesystem. Two hard links to the same file share the same inode number.
List Only Directories¶
Recursive Listing¶
Sort by Size¶
Internal Working¶
When you run ls, the following happens:
sequenceDiagram
participant Shell
participant ls
participant Kernel
participant VFS
participant Filesystem
Shell->>ls: execve("/usr/bin/ls", args)
ls->>Kernel: openat(AT_FDCWD, ".", O_RDONLY|O_DIRECTORY)
Kernel->>VFS: lookup path
VFS->>Filesystem: open directory inode
Filesystem-->>ls: file descriptor (fd)
ls->>Kernel: getdents64(fd, buf, bufsize)
Kernel->>Filesystem: read directory entries
Filesystem-->>ls: dirent structs (name + inode)
ls->>Kernel: stat(name) for each file (when -l)
Kernel-->>ls: struct stat (permissions, size, timestamps)
ls-->>Shell: formatted output to stdout Key system calls used by ls:
| System Call | Purpose |
|---|---|
openat() | Open the directory |
getdents64() | Read directory entries (efficient batch read) |
lstat() / stat() | Get file metadata for each entry |
readlink() | Resolve symlink targets (for -l) |
write() | Write formatted output to stdout |
Kernel Details¶
Directory Entries (dentries)¶
The kernel maintains a dentry cache (dcache) mapping filename strings to inode numbers. When ls calls getdents64(), the kernel:
- Looks up the directory's inode
- Reads the directory's data blocks from disk (or cache)
- Returns
linux_dirent64structures containing: d_ino— inode numberd_reclen— record lengthd_type— file type (DT_REG, DT_DIR, DT_LNK, etc.)d_name— null-terminated filename
Why ls -l is Slower¶
With -l, ls must call stat() (or lstat()) on every file to retrieve permissions, timestamps, and sizes. This results in N+1 system calls:
For large directories, this can be slow. Use -U (no sort) and pipe to head for fast checks.
inode and Hard Links¶
# Create a hard link
ln /etc/passwd /tmp/passwd-hardlink
# Both files share the same inode
ls -li /etc/passwd /tmp/passwd-hardlink
Both will show the same inode number. The link count in ls -l output shows how many directory entries point to this inode.
Performance Notes¶
Fast directory listing
For directories with millions of files:
Avoid ls in scripts
Parsing ls output is unreliable — filenames can contain spaces, newlines, and special characters. Use find, globbing, or arrays instead:
Best Practices¶
- Always use
ls -lhoverls -lfor human-readable sizes - Use
--color=autoin your shell alias (usually already set in.bashrc) - In scripts, prefer
findor glob patterns over parsingls - Use
ls -lawhen debugging hidden config files - Use
ls -lS | headto quickly find the largest files
Common Mistakes¶
Parsing ls output in scripts
ls aliases can hide real behaviour
Many distros alias ls to ls --color=auto. If you see unexpected color in a script, use /usr/bin/ls or \ls to bypass aliases.
Troubleshooting¶
| Problem | Cause | Solution |
|---|---|---|
ls: cannot access '/path': No such file or directory | Path doesn't exist | Check path spelling; use find to search |
ls: cannot open directory '/root': Permission denied | Insufficient permissions | Use sudo ls /root |
| Output is not sorted | Using -U | Remove -U or add -t/-S |
| Colors not showing | --color=never or piped | Add --color=always or use ls interactively |
Symlinks shown as ? | Broken symlink | Use ls -la to see target; readlink -f to resolve |
Related Commands¶
| Command | Description |
|---|---|
dir | GNU version similar to ls |
find | Advanced file search with metadata filtering |
stat | Detailed file metadata (all timestamps, inode info) |
file | Determine file type by content inspection |
tree | Recursive directory tree view |
lsof | List open files by process |
du | Disk usage per directory |
exa / eza | Modern ls replacement with git integration |
Interview Questions¶
What is the difference between . and ..?
. refers to the current directory. .. refers to the parent directory. Both are special directory entries maintained by the kernel in every directory. They are always visible with ls -a.
What does the number 2 mean in ls -l output?
It is the hard link count — the number of directory entries that reference this inode. For a regular file, this is usually 1. Directories always have at least 2 (the directory entry itself and the . inside it). Each subdirectory adds another via ...
Why does ls -l show sizes in bytes but du shows different numbers?
ls -l shows the logical file size (content size). du shows the disk usage — the actual blocks allocated on disk. Due to sparse files, filesystem block alignment, and metadata overhead, these numbers differ.
What is getdents64 and why is it used instead of readdir?
getdents64 is a Linux-specific system call that reads multiple directory entries in a single call (batch), making it much faster than the POSIX readdir() which calls the kernel once per entry. Modern ls uses getdents64 internally.
Practice Exercises¶
Exercise 1: Understand the output
Run ls -la /etc/ssh/ and explain every field in the output of sshd_config.
Exercise 2: Find large files
List the 5 largest files in /var/log sorted by size, showing human-readable sizes.
Exercise 3: Count files
Count the number of regular files in /usr/bin without using find.
Exercise 4: Inode inspection
Create a hard link and verify both files share the same inode number.