108 entries · 9 sections
Linux Commands Cheat Sheet
The Linux and macOS terminal commands that come up every day — moving around, finding files, reading logs, fixing permissions, killing processes, checking the network and unpacking archives. Ordered by what you are trying to do rather than alphabetically.
Moving around and listing
| Syntax | What it does |
|---|---|
pwd | Print the directory you are currently in. |
ls -lh | Long listing with human-readable file sizes. |
ls -la | Long listing including dotfiles. |
ls -lt | Sort by modification time, newest first. Add -r to reverse it. |
cd - | Return to the previous directory. |
cd ~ | Go to your home directory. |
tree -L 2 | Draw the directory tree two levels deep. |
du -sh * | Size of each item in the current directory. |
du -h --max-depth=1 | sort -h | Find which subdirectory is eating the disk. On macOS and BSD the flag is du -d 1 -h. |
df -h | Free space per mounted filesystem. |
Files and directories
| Syntax | What it does |
|---|---|
touch file | Create an empty file, or update an existing file's timestamp. |
mkdir -p a/b/c | Create a directory and any missing parents. |
cp file copy | Copy a file. |
cp -r dir/ dest/ | Copy a directory and everything inside it. |
cp -a src/ dest/ | Archive copy: recursive and preserving permissions, timestamps and links. |
mv old new | Move or rename. Same command for both. |
rm file | Delete a file. |
rm -rf dir/ | Delete a directory and its contents without prompting. There is no undo. |
ln -s /target link | Create a symbolic link. |
stat file | Size, permissions, inode and the access, modify and change times. |
file archive.bin | Guess a file's real type from its contents rather than its extension. |
readlink -f path | Resolve a path to its absolute, symlink-free form. |
Reading and slicing files
| Syntax | What it does |
|---|---|
cat file | Print a whole file. |
less file | Page through a file. / searches, n repeats, q quits. |
head -n 20 file | The first 20 lines. |
tail -n 50 file | The last 50 lines. |
tail -f app.log | Follow a log as it is written. |
tail -F app.log | Follow, and reopen the file if it is rotated out from under you. |
wc -l file | Count lines. -w counts words, -c counts bytes. |
sort file | uniq -c | sort -rn | Count duplicate lines, most frequent first. uniq only collapses adjacent lines, hence the first sort. |
cut -d, -f2 data.csv | Take the second comma-separated field of every line. |
awk '{print $1, $3}' file | Print selected whitespace-separated columns. |
sed -i 's/old/new/g' file | Replace text in place. On macOS the flag needs an argument: sed -i '' ... |
diff -u a.txt b.txt | Unified diff between two files. |
Searching
| Syntax | What it does |
|---|---|
grep "text" file | Print the lines that contain the text. |
grep -r "text" . | Search a whole directory tree. |
grep -i "text" file | Case-insensitive. |
grep -n "text" file | Show line numbers with each match. |
grep -v "text" file | Invert: print the lines that do not match. |
grep -E "a|b" file | Use extended regular expressions. -P switches to PCRE where available. |
grep -c "text" file | Count matching lines instead of printing them. |
grep -rl "text" . | List only the names of the files that contain a match. |
grep -A3 -B3 "text" file | Show three lines of context after and before each match. |
find . -name "*.log" | Find files by name pattern. Quote the pattern so the shell does not expand it. |
find . -type f -mtime -1 | Files modified in the last 24 hours. |
find . -size +100M | Files larger than 100 MB. |
find . -name "*.tmp" -delete | Find and delete in one pass. Run it without -delete first. |
command -v node | Where a command resolves from, and whether it exists at all. |
Permissions and ownership
| Syntax | What it does |
|---|---|
chmod +x script.sh | Make a file executable. |
chmod 644 file | Owner reads and writes, everyone else reads. The normal setting for a file. |
chmod 755 dir | Owner full, everyone else read and execute. The normal setting for a directory. |
chmod 600 ~/.ssh/id_ed25519 | Owner only. Private keys and secrets need this or SSH refuses them. |
chmod -R 755 dir/ | Apply recursively through a tree. |
chown user:group file | Change the owning user and group. |
chown -R user: dir/ | Change ownership through a whole tree. |
umask 022 | The default permission mask applied to newly created files. |
sudo command | Run a single command as root. |
sudo -u www-data command | Run a command as another user. |
id | Your user id, group id and every group you belong to. |
groups user | List the groups a user belongs to. |
Processes and jobs
| Syntax | What it does |
|---|---|
ps aux | Every process with its user, CPU and memory use. |
ps aux | grep node | Find a process by name. |
top | Live process monitor. htop is the friendlier version if it is installed. |
kill <pid> | Ask a process to shut down cleanly (SIGTERM). |
kill -9 <pid> | Force-kill (SIGKILL). Last resort — no cleanup handler runs. |
pkill -f "node server" | Kill by matching the full command line. |
pgrep -af node | List the pids and command lines that match a name. |
jobs | List the background jobs of this shell. |
fg %1 / bg %1 | Bring job 1 to the foreground / resume it in the background. |
nohup cmd & | Run a command that survives the terminal closing. |
lsof -i :3000 | Which process is holding port 3000. |
time cmd | Measure how long a command takes. |
Networking
| Syntax | What it does |
|---|---|
curl -I https://example.com | Fetch just the response headers. |
curl -L -o out.zip <url> | Download to a file, following redirects. |
curl -s <url> | head | Fetch quietly and inspect the start of the body. |
wget <url> | Download a file. -c resumes an interrupted download. |
ping -c 4 example.com | Send four packets and report the round-trip times. |
dig example.com +short | Resolve a hostname, output trimmed to the answer. |
ss -tulpn | Listening TCP and UDP sockets with the processes behind them. Replaces netstat. |
ip a | Network interfaces and their addresses. |
ip r | The routing table. |
traceroute example.com | Show the hops between you and a host. |
nc -zv host 22 | Test whether a TCP port is reachable. |
Archives and transfers
| Syntax | What it does |
|---|---|
tar -czf a.tar.gz dir/ | Create a gzip-compressed tarball. |
tar -xzf a.tar.gz | Extract a gzip tarball. |
tar -tzf a.tar.gz | List the contents without extracting anything. |
tar -xzf a.tar.gz -C /dest | Extract into a specific directory. |
tar -cJf a.tar.xz dir/ | Create an xz tarball — slower, noticeably smaller. |
zip -r a.zip dir/ | Create a zip archive. |
unzip a.zip -d dest/ | Extract a zip into a directory. |
gzip file / gunzip file.gz | Compress or decompress a single file in place. |
rsync -avz src/ dest/ | Copy only what changed, preserving permissions and timestamps. |
rsync -avz --delete src/ user@host:/dest/ | Mirror a directory to a remote host, deleting what is no longer in the source. |
scp file user@host:/path | Copy a file over SSH. |
System, services and packages
| Syntax | What it does |
|---|---|
uname -a | Kernel version and machine architecture. |
cat /etc/os-release | Distribution name and version. |
free -h | Memory and swap use. |
uptime | How long the machine has been up, plus the load averages. |
systemctl status nginx | Whether a service is running, with its recent log lines. |
systemctl restart nginx | Restart a service. start, stop and reload work the same way. |
systemctl enable --now nginx | Start a service and make it start at boot. |
journalctl -u nginx -f | Follow one service's logs. |
journalctl -p err -b | Errors only, from the current boot. |
sudo apt update && sudo apt install pkg | Debian and Ubuntu: refresh the index, then install. |
sudo dnf install pkg | Fedora, RHEL and derivatives. |
sudo pacman -S pkg | Arch and derivatives. |
apk add pkg | Alpine, which is what most slim container images use. |
history | grep ssh | Search your own command history. |
Worth knowing
- Almost every difference you hit between a Linux server and a Mac terminal is GNU versus BSD tooling. sed -i needs an empty argument on macOS, du uses -d instead of --max-depth, and readlink -f does not exist until you install coreutils. Install coreutils with Homebrew and the g-prefixed commands (gsed, gdu) behave like the server's.
- Test destructive find and rsync commands before running them. find without -delete just prints what it matched, and rsync --dry-run shows exactly what it would transfer or remove. Both take two seconds and have saved entire directories.
- Ctrl+R searches your shell history backwards as you type, Ctrl+A and Ctrl+E jump to the start and end of the line, and Ctrl+W deletes the previous word. These readline bindings work in bash, zsh, psql and most REPLs.
Try a snippet instead of reading about it
Reference is faster when you can run the thing. Paste a snippet into AltF Code, the free in-browser editor — real syntax highlighting for HTML, CSS, JavaScript, Python, SQL, JSON and more, with HTML, CSS and JavaScript running live in the preview. No install and no sign-up.
Open the editorLinux Commands — common questions
- What is the difference between chmod 644 and chmod 755?
- The three digits are owner, group and others, and each is read (4) plus write (2) plus execute (1). 644 means the owner can read and write while everyone else can only read — right for ordinary files. 755 adds execute for everyone, which directories need in order to be entered and scripts need in order to run.
- How do I find which process is using a port?
- Run sudo lsof -i :3000 to see the process holding that port, or sudo ss -tulpn | grep 3000 for the same information from the socket table. Once you have the pid, kill <pid> asks it to stop and kill -9 <pid> forces it.
- How do I find large files that are filling the disk?
- Start with df -h to see which filesystem is full, then du -h --max-depth=1 /var | sort -h to walk down into the biggest directory one level at a time. For a direct hunt, find / -type f -size +500M 2>/dev/null lists every very large file.
- What is the difference between grep, find and locate?
- grep searches inside file contents, find searches the filesystem by name, size, time and type and can act on what it finds, and locate answers name queries instantly from a prebuilt database — which means it can be out of date until updatedb runs.