Skip to the content.

Linux Command Cheat Sheet: Essential Commands by Task, With Examples

A Linux command cheat sheet organized by task, not alphabetically: find a file, free disk space, see what is using a port, follow a log, fix permissions, copy files over SSH, schedule a job. Every entry has a working example and a short explanation of the flags. It covers the commands you actually use on Ubuntu, Debian, Fedora, RHEL, Arch and most servers and containers, plus shell productivity tricks, troubleshooting recipes and modern alternatives to classic tools. Useful for beginners, developers, DevOps and sysadmins, and for anyone preparing for a Linux interview or certification.

Last reviewed: December 2026. Examples assume GNU coreutils and a bash or zsh shell, as on most Linux distributions. Where macOS (BSD tools) differs, it is noted. Commands that change the system are marked with sudo; read them before running.

Table of Contents


How to read this cheat sheet

Getting help

Task Command
Full manual for a command man tar (search inside with /word, n next, q quit)
Short usage summary tar --help
Search manuals by keyword man -k compress (or apropos compress)
Practical examples tldr tar (community examples, install the tldr client)
Is it a builtin, alias or file? type cd, type ll, command -v python3
Where is a binary? which git
Help for shell builtins help cd (bash)

Task Command Notes
Where am I? pwd Print working directory
List files ls  
List with details, hidden files, human sizes ls -lah -l long, -a all, -h human-readable
Sort by modification time, newest first ls -lt Add -r to reverse
Sort by size ls -lS  
Tree view tree -L 2 Install tree; -L limits depth
Go to a directory cd /var/log  
Go home cd or cd ~  
Go back to the previous directory cd -  
Up one level cd ..  
Push/pop a directory stack pushd /etc then popd  

Important directories: /etc (configuration), /var/log (logs), /home/<user> (user files), /tmp (temporary, often cleared on reboot), /usr/bin (programs), /opt (third-party software), /proc and /sys (kernel and process information), /mnt and /media (mount points).

Create, copy, move and delete

Task Command
Create an empty file (or update its timestamp) touch notes.txt
Create a directory (with parents) mkdir -p projects/app/src
Copy a file cp report.pdf backup/
Copy a directory recursively, keeping attributes cp -a src/ dest/
Copy without overwriting existing files cp -n a.txt b.txt
Move or rename mv old.txt new.txt
Ask before overwriting mv -i a.txt dir/
Delete a file rm file.txt
Delete a directory and its contents rm -r build/ (add -f to skip prompts; be careful)
Delete an empty directory rmdir empty/
Create a symbolic link ln -s /opt/app/current/bin/app /usr/local/bin/app
Show where a symlink points readlink -f /usr/local/bin/app
Create a file with content printf 'line one\nline two\n' > file.txt
Make a temporary file or directory mktemp / mktemp -d
Bulk rename (.jpeg to .jpg) for f in *.jpeg; do mv -- "$f" "${f%.jpeg}.jpg"; done

View and edit files

Task Command
Print a whole file cat file.txt
Page through a file less file.txt (/ search, G end, g start, F follow, q quit)
First / last 20 lines head -n 20 file / tail -n 20 file
Follow a growing log tail -f /var/log/syslog (tail -F survives log rotation)
Number lines nl file or cat -n file
Show non-printing characters (tabs, line endings) cat -A file (macOS: cat -et file)
Compare two files diff -u old.conf new.conf
Compare side by side diff -y a b or sdiff a b
Check a file’s type file mystery.bin
Hex dump xxd file \| head
Edit in the terminal nano file (beginner-friendly), vim file (i insert, Esc, :wq save and quit, :q! quit without saving)
Count lines, words, bytes wc -l file, wc -w file, wc -c file
Checksums sha256sum file.iso (macOS: shasum -a 256 file.iso)

Find files

# By name (case-insensitive), under the current directory
find . -iname '*.pdf'

# Only files / only directories
find /var/log -type f -name '*.log'
find . -type d -name node_modules -prune

# Modified in the last 24 hours (-mtime -1) or more than 30 days ago (+30)
find . -type f -mtime -1
find /tmp -type f -mtime +30

# Bigger than 100 MB
find / -xdev -type f -size +100M 2>/dev/null

# Empty files and directories
find . -empty

# Run a command on each result (the + batches arguments, like xargs)
find . -name '*.tmp' -exec rm -- {} +

# Delete matches (preview first by running without -delete!)
find . -name '*.pyc' -delete

# Files owned by a user / with specific permissions
find /srv -user www-data
find . -type f -perm -o+w      # world-writable files

# Fast lookup using a prebuilt index (updatedb refreshes it)
locate nginx.conf

2>/dev/null hides “Permission denied” noise. -xdev stays on one file system (skips /proc, network mounts).

Search inside files

grep 'error' app.log                  # lines containing "error"
grep -i 'error' app.log               # case-insensitive
grep -n 'TODO' *.py                   # show line numbers
grep -rn 'API_KEY' .                  # recursive with line numbers
grep -rl 'deprecated' src/            # only file names
grep -v '^#' config.ini               # lines NOT matching (strip comments)
grep -E 'warn|error' app.log          # extended regex (alternation)
grep -w 'id' file                     # whole words only
grep -c 'GET' access.log              # count matching lines
grep -C 3 'Exception' app.log         # 3 lines of context (-A after, -B before)
grep -o '[0-9]\{1,3\}\(\.[0-9]\{1,3\}\)\{3\}' access.log | sort | uniq -c | sort -rn | head
                                      # top IP addresses in a log
rg 'fn main' --type rust              # ripgrep: fast, respects .gitignore

Text processing

Task Command
Sort lines sort names.txt (-r reverse, -n numeric, -h human sizes, -u unique)
Sort by the 3rd column, numerically sort -k3,3n data.txt
Remove adjacent duplicates / count them sort file \| uniq / sort file \| uniq -c \| sort -rn
Cut columns by delimiter cut -d, -f1,3 users.csv
Cut characters cut -c1-10 file
Replace text (print) sed 's/http:/https:/g' links.txt
Replace text in place (with backup) sed -i.bak 's/foo/bar/g' file.txt (macOS: sed -i '' 's/foo/bar/g' file)
Delete lines matching a pattern sed '/^$/d' file (delete empty lines)
Print lines 10 to 20 sed -n '10,20p' file
Print a column awk '{print $1}' access.log
Sum a column awk '{sum += $5} END {print sum}' file
Filter rows by a condition awk -F, '$3 > 100 {print $1, $3}' sales.csv
Translate or delete characters tr 'a-z' 'A-Z' < file, tr -d '\r' < win.txt > unix.txt
Join lines side by side paste names.txt ages.txt
Number of unique values in column 1 cut -d' ' -f1 access.log \| sort -u \| wc -l
Reverse lines tac file (macOS: tail -r file)
Format columns column -t -s, data.csv
Pretty-print / query JSON jq '.' data.json, jq -r '.items[].name' data.json
Filter JSON jq '.[] \| select(.status == "active") \| .id' users.json

Pipes, redirection and shell basics

command > out.txt          # stdout to file (overwrite)
command >> out.txt         # append
command 2> err.txt         # stderr to file
command > all.txt 2>&1     # stdout and stderr to the same file
command &> all.txt         # same, bash shorthand
command < input.txt        # file as stdin
command | tee out.txt      # show output AND save it
command | sudo tee /etc/x  # write to a root-owned file (sudo with > does not work)
cmd1 && cmd2               # run cmd2 only if cmd1 succeeded
cmd1 || cmd2               # run cmd2 only if cmd1 failed
cmd1 ; cmd2                # run both regardless
echo $?                    # exit status of the last command (0 = success)
$(command)                 # command substitution: echo "Today is $(date +%F)"
!!                         # repeat the last command (sudo !! is a classic)
xargs                      # turn input lines into arguments:
find . -name '*.log' -print0 | xargs -0 gzip      # -print0/-0 handle spaces in names
ls *.png | xargs -n1 -P4 optipng                    # 4 in parallel

Quoting rules: use double quotes around variables ("$file") so names with spaces work; use single quotes when you want no expansion at all ('$HOME stays literal').

Brace expansion and globbing:

mkdir -p project/{src,tests,docs}
cp config.yml{,.bak}          # copies config.yml to config.yml.bak
ls *.{jpg,png}
ls **/*.md                    # recursive glob (bash: shopt -s globstar; zsh: built in)

Permissions and ownership

-rwxr-x--- 1 alice devs 4096 Dec  1 10:00 deploy.sh
 └┬┘└┬┘└┬┘
  │  │  └── others: no access
  │  └───── group (devs): read + execute
  └──────── owner (alice): read + write + execute
Permission On a file On a directory Octal
r Read contents List names 4
w Modify contents Create, delete, rename entries 2
x Run as a program Enter (cd) and access entries 1
Task Command
Make a script executable chmod +x deploy.sh
Owner rw, group r, others none chmod 640 secrets.env
Typical file / directory modes 644 for files, 755 for directories and scripts
Private SSH key chmod 600 ~/.ssh/id_ed25519
Recursively fix: dirs 755, files 644 find site -type d -exec chmod 755 {} + and find site -type f -exec chmod 644 {} +
Remove write for group and others chmod go-w file
Change owner and group sudo chown alice:devs file
Recursively sudo chown -R www-data:www-data /var/www/app
Change group only chgrp devs file
Show numeric permissions stat -c '%a %n' * (macOS: stat -f '%Lp %N' *)
Default permissions for new files umask (e.g. 022 gives 644 files, 755 directories)
Access control lists setfacl -m u:bob:r file, getfacl file

Special bits: setuid (chmod u+s, runs as the file owner), setgid on directories (chmod g+s, new files inherit the group, handy for shared folders), sticky bit (chmod +t, only owners can delete their files, as on /tmp).

Never fix a permission problem with chmod -R 777. Find out which user needs access and grant exactly that.

Users, groups and sudo

Task Command
Who am I? whoami, id
Who is logged in who, w
Create a user with a home directory sudo useradd -m -s /bin/bash alice (Debian/Ubuntu also offer the interactive sudo adduser alice)
Set or change a password sudo passwd alice / passwd for yourself
Add a user to a group sudo usermod -aG docker alice (-a append is essential; log out and in to apply)
List a user’s groups groups alice
Create a group sudo groupadd devs
Delete a user and home sudo userdel -r alice
Switch user su - alice or sudo -iu alice
Run one command as root sudo systemctl restart nginx
Edit sudoers safely sudo visudo (validates syntax before saving)
Lock / unlock an account sudo usermod -L alice / -U
Last logins last, lastlog

Processes and jobs

Task Command
List all processes ps aux
Process tree ps auxf or pstree -p
Find a process by name pgrep -a nginx (-a shows the command line)
Interactive monitor top (P sort by CPU, M by memory, k kill, q quit) or htop
Gracefully stop a process kill <pid> (sends SIGTERM)
Force stop kill -9 <pid> (SIGKILL, last resort: no cleanup)
Stop by name pkill -f 'python app.py'
Reload configuration kill -HUP <pid> (many daemons reload on SIGHUP)
Run in the background long_task &
List background jobs jobs
Suspend / resume Ctrl+Z, then bg (background) or fg (foreground)
Keep running after logout nohup ./script.sh > out.log 2>&1 & or use tmux/screen
Start with lower priority nice -n 10 ./backup.sh; change later with renice +5 -p <pid>
Run with a timeout timeout 30s curl https://example.com
Repeat a command every 2 s watch -n 2 'df -h'
Measure run time time make

Common signals: SIGTERM (15) asks to exit, SIGKILL (9) forces exit, SIGINT (2) is Ctrl+C, SIGHUP (1) often means reload, SIGSTOP/SIGCONT pause and resume.

System information

Task Command
Distribution and version cat /etc/os-release
Kernel version uname -r (uname -a for everything)
Hostname hostname / hostnamectl
Uptime and load average uptime
CPU details lscpu, nproc (number of cores)
Memory free -h
Hardware summary sudo lshw -short, lspci, lsusb
Block devices lsblk
Kernel messages sudo dmesg -T \| tail
Date, time, time zone date, timedatectl
Environment and shell echo $SHELL, env
Logged-in sessions loginctl list-sessions

Disk usage and storage

Task Command
Free space per file system df -h
Inode usage (many tiny files) df -i
Size of a directory du -sh /var/log
Biggest items in the current directory du -sh -- * .[!.]* 2>/dev/null \| sort -h \| tail -20
Biggest directories, one level deep sudo du -h --max-depth=1 / 2>/dev/null \| sort -h (macOS: du -h -d 1)
Interactive explorer ncdu /
List disks and partitions lsblk -f (shows file systems and UUIDs)
Mount / unmount sudo mount /dev/sdb1 /mnt/data, sudo umount /mnt/data
Persistent mounts Add a line with the UUID to /etc/fstab, then test with sudo mount -a
Check a file system (unmounted) sudo fsck /dev/sdb1
Find deleted files still holding space sudo lsof +L1
Clean old journal logs sudo journalctl --vacuum-time=7d
Clean package caches sudo apt clean / sudo dnf clean all

Networking

Task Command
IP addresses ip -br addr (brief) or ip addr
Routes and default gateway ip route
Interface status ip -br link
Listening ports and owning processes sudo ss -tulpn (t TCP, u UDP, l listening, p process, n numeric)
Who uses port 8080? sudo ss -ltnp 'sport = :8080' or sudo lsof -i :8080
Test reachability ping -c 4 example.com
Path to a host traceroute example.com or mtr example.com (live)
DNS lookup dig example.com +short, dig MX example.com, host example.com
Which DNS server answers resolvectl status (systemd-resolved) or cat /etc/resolv.conf
Test a TCP port nc -zv example.com 443
HTTP headers only curl -I https://example.com
Check a TLS certificate openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null \| openssl x509 -noout -dates -subject
Public IP address curl -s https://ifconfig.me
Network manager CLI nmcli device status, nmcli connection show
Hosts file overrides /etc/hosts
Capture packets sudo tcpdump -i any port 443 -n

ifconfig, netstat and route come from the older net-tools package and are not installed by default on many current distributions; ip and ss (iproute2) replace them.

SSH and remote copies

# Connect
ssh alice@server.example.com
ssh -p 2222 alice@server.example.com

# Create a key (Ed25519 is the modern default) and install it on a server
ssh-keygen -t ed25519 -C "alice@laptop"
ssh-copy-id alice@server.example.com

# Run a single remote command
ssh alice@server 'df -h /'

# Copy files
scp report.pdf alice@server:/home/alice/
scp -r alice@server:/var/log/app ./logs/

# Sync directories efficiently (only changes), with progress; trailing slash matters
rsync -avz --progress ./site/ alice@server:/var/www/site/
rsync -avz --delete ./site/ alice@server:/var/www/site/   # mirror: removes extra files on the target
rsync -avzn ./site/ alice@server:/var/www/site/            # -n dry run: show what would change

# Port forwarding: reach a remote database on localhost:5433
ssh -L 5433:localhost:5432 alice@server

# Jump through a bastion host
ssh -J bastion.example.com alice@10.0.0.5

# Keep a connection alive / reuse connections: put this in ~/.ssh/config
# ~/.ssh/config
Host prod
    HostName server.example.com
    User alice
    Port 22
    IdentityFile ~/.ssh/id_ed25519
    ServerAliveInterval 60

Then just ssh prod, scp file prod:, rsync -a dir/ prod:dir/.

Server hardening basics (in /etc/ssh/sshd_config, then sudo systemctl reload ssh or sshd depending on the distribution): PasswordAuthentication no once keys work, PermitRootLogin no, and test the new config in a second session before closing the first.

Download files and call APIs

curl -O https://example.com/file.tar.gz               # save with the remote name
curl -L -o app.zip https://example.com/latest         # follow redirects, choose the name
curl -fsSL https://example.com/install.sh | less      # READ install scripts before piping to sh
curl -C - -O https://example.com/big.iso              # resume a download
wget -c https://example.com/big.iso                   # same with wget
wget -r -np -k https://example.com/docs/              # mirror a docs folder for offline use

# APIs
curl -s https://api.example.com/users/1 | jq .
curl -X POST https://api.example.com/items \
  -H 'Content-Type: application/json' \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"name": "widget"}'
curl -w '%{http_code} %{time_total}s\n' -o /dev/null -s https://example.com   # status and timing

-f makes curl fail on HTTP errors (useful in scripts), -s silences progress, -S still shows errors, -L follows redirects.

Archives and compression

Task Command
Create a .tar.gz tar -czf backup.tar.gz project/
Extract a .tar.gz tar -xzf backup.tar.gz
Extract into a directory tar -xzf backup.tar.gz -C /opt/
List contents tar -tzf backup.tar.gz
Create with zstd (fast, small) tar --zstd -cf backup.tar.zst project/
Create with xz (smallest, slow) tar -cJf backup.tar.xz project/
Exclude paths tar -czf app.tar.gz --exclude=node_modules --exclude=.git app/
Compress / decompress one file gzip file / gunzip file.gz (-k keeps the original)
Zip / unzip zip -r site.zip site/ / unzip site.zip -d site/
Read compressed logs directly zcat app.log.gz \| grep error or zgrep error app.log.gz

Mnemonic for tar flags: create, extract, t list, z gzip, J xz, f file name follows, v verbose.

Package management

Task Debian / Ubuntu (apt) Fedora / RHEL (dnf) Arch (pacman) Alpine (apk)
Refresh package lists sudo apt update (automatic) sudo dnf check-update sudo pacman -Sy sudo apk update
Upgrade everything sudo apt upgrade sudo dnf upgrade sudo pacman -Syu sudo apk upgrade
Install sudo apt install nginx sudo dnf install nginx sudo pacman -S nginx sudo apk add nginx
Remove sudo apt remove nginx sudo dnf remove nginx sudo pacman -R nginx sudo apk del nginx
Search apt search nginx dnf search nginx pacman -Ss nginx apk search nginx
Show info apt show nginx dnf info nginx pacman -Si nginx apk info -a nginx
Which package owns a file dpkg -S /usr/bin/curl rpm -qf /usr/bin/curl pacman -Qo /usr/bin/curl apk info --who-owns /usr/bin/curl
List installed apt list --installed dnf list --installed pacman -Q apk info
Remove unused dependencies sudo apt autoremove sudo dnf autoremove sudo pacman -Rns $(pacman -Qdtq) (automatic)

Universal formats: flatpak install flathub <app> and snap install <app> for desktop apps across distributions. On Arch, do not run pacman -Sy <pkg> without -u (partial upgrades can break the system).

Services and logs (systemd)

Task Command
Status of a service systemctl status nginx
Start / stop / restart sudo systemctl start nginx / stop / restart
Reload configuration without dropping connections sudo systemctl reload nginx
Start on boot (and now) sudo systemctl enable --now nginx
Disable on boot sudo systemctl disable nginx
List running services systemctl list-units --type=service --state=running
List failed units systemctl --failed
After editing unit files sudo systemctl daemon-reload
Override settings safely sudo systemctl edit nginx (creates a drop-in file)
Logs for a service journalctl -u nginx
Follow logs live journalctl -u nginx -f
Logs since a time journalctl -u nginx --since "1 hour ago"
Only errors from this boot journalctl -p err -b
Kernel log journalctl -k
Journal disk usage journalctl --disk-usage
Classic log files /var/log/syslog (Debian/Ubuntu), /var/log/messages (RHEL family), /var/log/auth.log (logins)

A minimal service for your own app:

# /etc/systemd/system/myapp.service
[Unit]
Description=My app
After=network-online.target
Wants=network-online.target

[Service]
User=myapp
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/server --port 8080
Restart=on-failure
EnvironmentFile=/etc/myapp.env

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
journalctl -u myapp -f

Scheduling jobs

crontab -e        # edit your jobs
crontab -l        # list them
# ┌ minute (0-59)
# │ ┌ hour (0-23)
# │ │ ┌ day of month (1-31)
# │ │ │ ┌ month (1-12)
# │ │ │ │ ┌ day of week (0-7, 0 and 7 = Sunday)
# │ │ │ │ │
  0 3 * * *   /opt/scripts/backup.sh >> /var/log/backup.log 2>&1   # every day at 03:00
  */15 * * * * /opt/scripts/healthcheck.sh                          # every 15 minutes
  0 9 * * 1-5 /opt/scripts/report.sh                                # weekdays at 09:00
  @reboot     /opt/scripts/on-boot.sh

Cron runs with a minimal environment: use absolute paths and redirect output to a log. Check expressions with crontab.guru.

systemd timers are the modern alternative (logging in the journal, missed runs with Persistent=true):

# /etc/systemd/system/backup.timer   (pairs with backup.service)
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target
sudo systemctl enable --now backup.timer
systemctl list-timers

One-off later: echo '/opt/scripts/report.sh' | at 18:00.

Environment variables and shell config

echo "$PATH"                          # where the shell looks for programs
export EDITOR=vim                     # set for this shell and its children
export PATH="$HOME/.local/bin:$PATH"  # prepend a directory
unset EDITOR
env | sort                            # list all variables
MY_VAR=1 ./script.sh                  # set only for one command
File Loaded by
~/.bashrc Interactive bash shells (aliases, prompt, functions)
~/.bash_profile or ~/.profile Login shells (environment variables)
~/.zshrc Interactive zsh shells
/etc/environment System-wide variables (simple KEY=value lines)

Apply changes with source ~/.bashrc (or open a new terminal).

Useful aliases:

alias ll='ls -lah'
alias ..='cd ..'
alias gs='git status'
alias ports='sudo ss -tulpn'
alias myip='curl -s https://ifconfig.me; echo'

History tricks: history | grep ssh, Ctrl+R to search history interactively, !42 to rerun entry 42, !$ for the last argument of the previous command (mkdir newdir && cd !$).

Performance troubleshooting

A 60-second checklist when a server feels slow:

uptime                      # load averages (1, 5, 15 min) vs number of cores (nproc)
dmesg -T | tail             # kernel errors: out-of-memory kills, disk errors
vmstat 1 5                  # r = runnable processes, si/so = swapping, wa = I/O wait
free -h                     # memory and swap; "available" is what matters
top                         # who uses CPU and memory right now (or htop)
iostat -xz 1 3              # disk utilization and latency (sysstat package)
df -h; df -i                # full disks or exhausted inodes
ss -s                       # socket summary (connection counts)
journalctl -p err -b        # recent errors
Symptom Look at Typical fix
High load, low CPU use vmstat wa, iostat Slow disk or network storage; reduce I/O
Processes killed randomly dmesg -T \| grep -i oom Add memory or limits, fix the memory leak
Disk full df -h, du, lsof +L1 Delete or rotate logs, restart processes holding deleted files
“Too many open files” ulimit -n, ls /proc/<pid>/fd \| wc -l Raise LimitNOFILE in the systemd unit, fix leaks
What is a process doing? sudo strace -p <pid> Spot blocking system calls
Which files does it use? sudo lsof -p <pid>  

Firewall basics

Task Ubuntu (ufw) Fedora / RHEL (firewalld)
Status sudo ufw status verbose sudo firewall-cmd --state, --list-all
Allow SSH first! sudo ufw allow OpenSSH sudo firewall-cmd --permanent --add-service=ssh
Allow a port sudo ufw allow 443/tcp sudo firewall-cmd --permanent --add-port=443/tcp
Enable sudo ufw enable sudo systemctl enable --now firewalld
Apply permanent rules (immediate) sudo firewall-cmd --reload
Remove a rule sudo ufw delete allow 443/tcp sudo firewall-cmd --permanent --remove-port=443/tcp

Always allow SSH before enabling a firewall on a remote machine, or you will lock yourself out.


Recipes for common problems

Disk is full: what is taking the space?

df -h                                                   # which file system is full
sudo du -xh --max-depth=1 / 2>/dev/null | sort -h | tail # biggest top-level directories
sudo find / -xdev -type f -size +500M -exec ls -lh {} + 2>/dev/null
sudo journalctl --vacuum-size=500M                       # trim the systemd journal
sudo lsof +L1                                            # deleted files still open: restart that process

Port already in use

sudo ss -ltnp 'sport = :3000'   # see the PID and program
kill <pid>                      # or stop the service that owns it

Permission denied running a script

ls -l script.sh        # missing x?
chmod +x script.sh
head -1 script.sh      # correct shebang, e.g. #!/usr/bin/env bash
sed -i 's/\r$//' script.sh   # remove Windows line endings ("bad interpreter: ^M")

Find which config file sets a value

grep -rn 'max_connections' /etc/ 2>/dev/null

Replace a string in many files (preview, then apply)

grep -rl 'old.example.com' ./config
grep -rl 'old.example.com' ./config | xargs sed -i 's/old\.example\.com/new.example.com/g'

Run a long command that survives disconnects

tmux new -s work      # detach with Ctrl+B then D; reattach with: tmux attach -t work

Watch a log for errors and highlight them

tail -F /var/log/app.log | grep --line-buffered -iE 'error|exception'

Generate a random password or token

openssl rand -base64 32

Quickly serve the current directory over HTTP (local testing only)

python3 -m http.server 8000

Count files by extension

find . -type f -name '*.*' | sed 's/.*\.//' | sort | uniq -c | sort -rn | head

Show the 10 largest files in a directory tree

find . -type f -printf '%s %p\n' | sort -rn | head -10 | numfmt --to=iec --field=1

(-printf and numfmt are GNU; on macOS install coreutils/findutils or use du.)


Modern alternatives to classic tools

These are optional, widely packaged and mostly drop-in friendlier versions. Learn the classic tool first: it is always installed on servers.

Classic Modern alternative Why people like it
grep -r ripgrep (rg) Very fast, respects .gitignore, sane defaults
find fd Simpler syntax (fd pattern), fast, colored
cat bat Syntax highlighting, line numbers, Git markers
ls eza Colors, icons, Git status, tree view
du dust, ncdu Visual or interactive disk usage
top htop, btop Interactive, colorful, mouse support
cd zoxide (z) Jump to frequent directories by partial name
Ctrl+R history fzf Fuzzy finder for history, files, anything
man tldr Short practical examples
sed/awk on JSON jq Real JSON parsing; yq for YAML

Keyboard shortcuts in the terminal

Shortcut Action
Ctrl+C Interrupt the running command
Ctrl+D End of input / exit the shell
Ctrl+Z Suspend (resume with fg or bg)
Ctrl+L Clear the screen
Ctrl+R Search command history
Ctrl+A / Ctrl+E Jump to start / end of the line
Ctrl+U / Ctrl+K Delete to start / end of the line
Ctrl+W Delete the previous word
Alt+B / Alt+F Move back / forward one word
Tab / Tab Tab Complete / show completions
!! Previous command
Alt+. Insert the last argument of the previous command

Dangerous commands to double-check

Command Risk Safer habit
rm -rf <path> Deletes without asking; a stray space or empty variable can wipe the wrong tree Run ls <path> first; in scripts use "${dir:?}" so an empty variable aborts
chmod -R 777 / chown -R on / Breaks system security and services Target the exact directory and user
dd if=... of=/dev/sdX Overwrites a whole disk Check the device with lsblk twice
mkfs.* Formats a partition Same as above
> file Truncates the file instantly Use >> to append; enable set -o noclobber
curl ... \| sudo bash Runs unknown code as root Download, read, then run
kill -9 on databases No clean shutdown, possible corruption Try kill (SIGTERM) or systemctl stop first
sed -i across many files Hard to undo Use -i.bak, or commit to Git first

FAQ

What is the difference between Linux and Unix commands? Most everyday commands (ls, cp, grep, find) follow POSIX and work on Linux, macOS and BSD. Linux distributions usually ship the GNU versions, which add long options (--human-readable) and extra features. macOS uses BSD versions, so some flags differ (sed -i '', stat -f, du -d).

How do I learn Linux commands fast? Learn by task: navigation, files, search, permissions, processes and logs cover most daily work. Practice on a real machine or a free VM, read man pages for the commands you use often, and play a wargame like OverTheWire Bandit.

apt or apt-get? apt is the friendlier interactive command; apt-get has a stable output format, so prefer it in scripts.

How do I see which process uses a file or port? sudo lsof /path/to/file or sudo lsof -i :8080; for ports, sudo ss -ltnp also works.

Why does sudo echo text > /etc/file fail? The redirection is done by your shell, not by sudo. Use echo text | sudo tee /etc/file (or tee -a to append).

How do I make a command run at startup? Create a systemd service (see Services and logs) and enable it. @reboot in crontab also works for simple scripts.

What does 2>&1 mean? Send file descriptor 2 (stderr) to the same place as file descriptor 1 (stdout). Order matters: cmd > file 2>&1 captures both; cmd 2>&1 > file does not.

How can I check what a complex command does before running it? Paste it into explainshell.com, read the man page, and run destructive operations with a dry-run flag (rsync -n, find without -delete, sed without -i).

How do I write safer shell scripts? Start with #!/usr/bin/env bash and set -euo pipefail, quote every variable, and lint with ShellCheck.


Where to go next

  1. Read The Linux Command Line, a free book by William Shotts, at linuxcommand.org.
  2. Learn bash properly with the BashGuide and the GNU Bash manual.
  3. Use the man7.org Linux man pages and the GNU coreutils manual as references.
  4. Browse the Arch Wiki; it is useful even if you do not use Arch.
  5. Learn systemd with the systemctl and journalctl manuals.
  6. Go deeper on performance with Brendan Gregg’s Linux performance page.
  7. Practice with OverTheWire Bandit and keep tldr installed for quick examples.
  8. For server administration, read your distribution’s docs: Ubuntu Server or Fedora.

Contributing

PRs are welcome. Keep entries accurate and task-focused: every command needs a working example, flags should be explained, and anything distribution-specific or GNU-only must say so. Mark destructive commands clearly.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.