Linux Cheat Sheet
Quick reference for essential Linux commands, file permissions, process management, networking, and systemd.
File System
Navigation & Listing
| Command | Description |
|---|---|
pwd | Print working directory |
ls -la | List all files with details |
ls -lah | Human-readable file sizes |
ls -lt | Sort by modification time |
ls -lS | Sort by file size |
cd - | Go to previous directory |
cd ~ | Go to home directory |
tree -L 2 | Directory tree, 2 levels deep |
File Operations
| Command | Description |
|---|---|
cp file dest | Copy file |
cp -r dir dest | Copy directory recursively |
mv old new | Move or rename |
rm file | Delete file |
rm -rf dir | Delete directory recursively |
mkdir -p a/b/c | Create nested directories |
touch file | Create file or update timestamp |
ln -s target link | Create symbolic link |
stat file | Detailed file info |
rsync -avh --progress src/ dest/ | Copy/sync (trailing / on src = copy contents, not the dir) |
rsync -avz --delete src/ user@host:/dest/ | Mirror to a remote host (deletes extras at dest) |
tar -czf out.tar.gz dir/ | Create gzip archive |
tar -xzf out.tar.gz -C /target | Extract into a directory |
tar -tzf out.tar.gz | List archive contents |
file name | Detect file type |
realpath file | Absolute path, symlinks resolved |
File Content
| Command | Description |
|---|---|
cat file | Print entire file |
less file | Paginated viewer |
head -n 20 file | First 20 lines |
tail -n 20 file | Last 20 lines |
tail -f file | Follow file (live logs) |
wc -l file | Count lines |
sort file | Sort lines |
uniq | Remove adjacent duplicates |
sort file | uniq -c | Count occurrences |
cut -d',' -f1,3 file | Extract CSV columns 1 and 3 |
tr 'a-z' 'A-Z' | Translate characters |
diff file1 file2 | Compare files |
md5sum file | MD5 checksum |
sha256sum file | SHA-256 checksum |
Search
| Command | Description |
|---|---|
find / -name "*.log" | Find files by name |
find / -type f -size +100M | Find files larger than 100MB |
find / -mtime -7 | Modified in last 7 days |
find . -type f -exec chmod 644 {} \; | Find and execute command (once per file) |
find . -type f -exec chmod 644 {} + | Same, batching many files per call (faster) |
find . -name "*.tmp" -delete | Find and delete |
find . -type f -print0 | xargs -0 grep -l foo | Safe with spaces in filenames |
grep -r "pattern" /path | Search recursively |
grep -rn "pattern" /path | Search with line numbers |
grep -ri "pattern" /path | Case-insensitive |
grep -rl "pattern" /path | List matching files only |
grep -v "pattern" | Invert match |
grep -E "regex" file | Extended regex |
locate filename | Fast search (uses db; plocate on modern distros, refresh with updatedb) |
which command | Find command path |
command -v cmd | POSIX way to find a command (also sees aliases/functions) |
type cmd | Show whether cmd is an alias, builtin, function or file |
File Permissions
Permission Structure
-rwxr-xr-- 1 user group 4096 Jan 1 12:00 file
|[-][-][-]
| | | |
| | | +-- Others: r-- (read only)
| | +----- Group: r-x (read + execute)
| +-------- Owner: rwx (read + write + execute)
+---------- Type: - (file), d (directory), l (symlink)
Permission Values
| Symbol | Numeric | Meaning |
|---|---|---|
r | 4 | Read |
w | 2 | Write |
x | 1 | Execute |
- | 0 | No permission |
Common Permission Patterns
| Numeric | Symbolic | Use Case |
|---|---|---|
644 | -rw-r--r-- | Regular files |
755 | -rwxr-xr-x | Executables, directories |
600 | -rw------- | Private files (SSH keys) |
700 | -rwx------ | Private directories |
660 | -rw-rw---- | Group-shared files |
775 | -rwxrwxr-x | Group-shared directories |
chmod Commands
# Numeric
chmod 644 file
chmod 755 script.sh
chmod -R 755 dir/
# Symbolic
chmod u+x file # Add execute for owner
chmod g+w file # Add write for group
chmod o-r file # Remove read for others
chmod a+r file # Add read for all
chmod u=rwx,g=rx,o=r file
# Capital X: execute only on directories (and files already executable)
chmod -R u=rwX,g=rX,o= dir/
# Different modes for files and dirs
find dir -type d -exec chmod 755 {} +
find dir -type f -exec chmod 644 {} +
On a directory, r = list names, w = create/delete entries, x = enter it and access files inside. Deleting a file needs w on the directory, not on the file.
umask # default mask, e.g. 0022 -> new files 644, dirs 755
getfacl file # ACLs (a "+" after the mode in ls -l means ACLs exist)
setfacl -m u:alice:rw file
chown Commands
chown user file # Change owner
chown user:group file # Change owner and group
chown -R user:group dir/ # Recursive
chgrp group file # Change group only
Special Permissions
| Permission | Numeric | Effect |
|---|---|---|
| SUID | 4xxx | Execute as file owner |
| SGID | 2xxx | Execute as file group / inherit group in dir |
| Sticky | 1xxx | Only owner can delete in directory |
chmod 4755 file # SUID
chmod 2755 dir # SGID
chmod 1777 /tmp # Sticky bit (/tmp's real mode: drwxrwxrwt)
Process Management
Viewing Processes
| Command | Description |
|---|---|
ps aux | All processes with details |
ps aux --sort=-%mem | Sort by memory usage |
ps aux --sort=-%cpu | Sort by CPU usage |
ps -ef --forest | Process tree |
top | Interactive process monitor |
htop | Better interactive monitor |
pgrep -f "pattern" | Find PID by name/pattern |
pidof nginx | Find PID by exact name |
ps -o pid,ppid,stat,etime,cmd -p PID | Chosen columns for one process |
pstree -p | Process tree with PIDs |
lsof -p PID | Files and sockets a process has open |
strace -p PID -f -e trace=network | Trace syscalls of a running process |
ls -l /proc/PID/cwd /proc/PID/exe | Working dir and binary of a process |
cat /proc/PID/status | Memory (VmRSS), threads, state |
Managing Processes
| Command | Description |
|---|---|
kill PID | Graceful kill (SIGTERM) |
kill -9 PID | Force kill (SIGKILL) |
kill -HUP PID | Reload config (SIGHUP) |
killall name | Kill all by name |
pkill -f "pattern" | Kill by pattern |
nohup cmd & | Run in background, survive logout |
disown -h %1 | Detach an already-running job from the shell |
systemd-run --user --unit=job cmd | Run as a transient systemd unit (logs in journal) |
nice -n 10 cmd / renice -n 10 -p PID | Lower CPU priority |
timeout 30s cmd | Kill command after 30 seconds |
cmd & | Run in background |
jobs | List background jobs |
fg %1 | Bring job 1 to foreground |
bg %1 | Resume stopped job in background |
Ctrl+Z | Suspend current process |
Ctrl+C | Interrupt current process |
Signals
| Signal | Number | Meaning |
|---|---|---|
| SIGHUP | 1 | Hangup / reload |
| SIGINT | 2 | Interrupt (Ctrl+C) |
| SIGQUIT | 3 | Quit with core dump |
| SIGKILL | 9 | Force kill (cannot catch) |
| SIGTERM | 15 | Graceful termination |
| SIGSTOP | 19 | Pause (cannot catch) |
| SIGCONT | 18 | Resume |
| SIGTSTP | 20 | Terminal stop (Ctrl+Z, can be caught) |
| SIGUSR1 / SIGUSR2 | 10 / 12 | App-defined (e.g. reopen logs) |
| SIGPIPE | 13 | Wrote to a closed pipe |
Numbers are for x86 and ARM Linux; some are different on other architectures, so prefer names: kill -TERM PID. kill -l lists them all. An exit code of 128 + N means "killed by signal N" (137 = SIGKILL, 143 = SIGTERM).
Disk & Storage
| Command | Description |
|---|---|
df -h | Disk space by filesystem |
du -sh dir/ | Directory size |
du -h --max-depth=1 / | Size of top-level directories |
du -ah dir/ | sort -rh | head -20 | Largest files in directory |
lsblk | Block device list |
mount | Show mounted filesystems |
fdisk -l | List disk partitions |
ncdu / | Interactive disk usage (if installed) |
ionice -c 3 cmd | Run command with low IO priority |
df -i | Inode usage ("No space left" with free bytes = inodes exhausted) |
df -hT | Disk space with filesystem type |
findmnt | Mount tree (clearer than mount) |
lsblk -f | Block devices with filesystems and UUIDs |
blkid | UUIDs and labels (for /etc/fstab) |
lsof +L1 | Deleted files still held open (space not freed until process restarts) |
mount -a | Mount everything in /etc/fstab (test fstab edits before reboot) |
Networking
Network Information
| Command | Description |
|---|---|
ip addr show | Show IP addresses |
ip route show | Show routing table |
ss -tlnp | Listening TCP ports with PIDs |
ss -ulnp | Listening UDP ports |
ss -s | Socket statistics summary |
netstat -tlnp | Listening ports (legacy) |
hostname -I | Show all IP addresses |
cat /etc/resolv.conf | DNS configuration |
ip link show | Network interfaces |
ip -br a | Brief: one line per interface with IPs |
ip route get 8.8.8.8 | Which interface/gateway a destination uses |
ss -tanp state established | Established TCP connections with processes |
ss -tn dst :443 | Connections to port 443 |
resolvectl status | DNS servers when systemd-resolved manages /etc/resolv.conf |
ip neigh | ARP / neighbour table |
Connectivity Testing
| Command | Description |
|---|---|
ping -c 4 host | ICMP ping (4 packets) |
traceroute host | Trace packet route |
mtr host | Combines ping and traceroute |
curl -I url | HTTP headers only |
curl -v url | Verbose HTTP request |
curl -o /dev/null -w "%{http_code}" url | Just status code |
wget -q -O - url | Download to stdout |
dig domain | DNS lookup |
dig +short domain | DNS lookup (short) |
nslookup domain | DNS lookup (simpler) |
host domain | DNS lookup (simplest) |
dig @1.1.1.1 domain AAAA | Query a specific server / record type |
dig +trace domain | Follow delegation from the root |
getent hosts domain | Resolve like applications do (honours /etc/hosts, nsswitch) |
curl --resolve example.com:443:1.2.3.4 https://example.com | Test a host against a specific IP |
openssl s_client -connect host:443 -servername host | Inspect TLS handshake and cert |
tcpdump -i any -nn port 443 | Capture packets on a port |
Port & Connection Debugging
# Check if port is open
nc -zv host 80
# Check if port is open (with timeout)
timeout 3 bash -c "echo > /dev/tcp/host/80" && echo open || echo closed
# Listen on a port (OpenBSD netcat; traditional netcat needs: nc -l -p 8080)
nc -l 8080
# Send data to a port
echo "hello" | nc host 8080
# Check what is listening on a port
ss -tlnp | grep :8080
lsof -i :8080
Firewall (iptables/nftables)
# List rules
iptables -L -n -v
# Allow incoming port 80
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# Block an IP
iptables -A INPUT -s 1.2.3.4 -j DROP
# Allow established connections (conntrack replaces the deprecated "-m state --state")
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Save rules (Debian/Ubuntu)
iptables-save > /etc/iptables/rules.v4
On current distros iptables is usually the iptables-nft front end writing nftables rules. Native nftables and the common wrappers:
# nftables
nft list ruleset
nft add rule inet filter input tcp dport 80 accept
# ufw (Ubuntu)
ufw allow 22/tcp && ufw enable
ufw status numbered
# firewalld (RHEL/Fedora)
firewall-cmd --add-service=https --permanent && firewall-cmd --reload
firewall-cmd --list-all
SSH
# Connect
ssh user@host
# Connect with specific key
ssh -i ~/.ssh/key.pem user@host
# Port forwarding (local)
ssh -L 8080:localhost:3000 user@host
# Port forwarding (remote)
ssh -R 8080:localhost:3000 user@host
# SOCKS proxy
ssh -D 1080 user@host
# Jump through a bastion
ssh -J bastion.example.com user@internal-host
# Tunnel only, no shell (-N), in background (-f)
ssh -fN -L 5432:db.internal:5432 user@bastion
# Copy files
scp file user@host:/tmp/
rsync -avz -e ssh dir/ user@host:/srv/dir/
# Load key into agent once per session
eval "$(ssh-agent -s)" && ssh-add ~/.ssh/id_ed25519
# Fix "UNPROTECTED PRIVATE KEY FILE" / key ignored
chmod 700 ~/.ssh && chmod 600 ~/.ssh/id_ed25519 ~/.ssh/authorized_keys
# Remove a stale host key after a server rebuild
ssh-keygen -R host
# Copy SSH key to server
ssh-copy-id user@host
# Generate SSH key
ssh-keygen -t ed25519 -C "email@example.com"
# SSH config (~/.ssh/config)
# Host myserver
# HostName 1.2.3.4
# User deploy
# IdentityFile ~/.ssh/deploy_key
# Port 22
# ProxyJump bastion
# ServerAliveInterval 30
systemd
Service Management
| Command | Description |
|---|---|
systemctl start service | Start service |
systemctl stop service | Stop service |
systemctl restart service | Restart service |
systemctl reload service | Reload config without restart |
systemctl status service | Service status and recent logs |
systemctl enable service | Start on boot |
systemctl disable service | Do not start on boot |
systemctl is-active service | Check if running |
systemctl is-enabled service | Check if enabled |
systemctl list-units --type=service | List all services |
systemctl list-units --failed | List failed services |
systemctl daemon-reload | Reload unit files after changes |
systemctl enable --now service | Enable and start in one step |
systemctl edit service | Create a drop-in override (/etc/systemd/system/service.d/override.conf) |
systemctl cat service | Show the unit file plus all drop-ins |
systemctl show service -p Restart,MemoryMax | Show effective properties |
systemctl list-timers | Scheduled timers (systemd's cron) |
systemctl mask service | Make a service impossible to start |
systemctl reset-failed | Clear failed state |
systemd-analyze blame | Slowest units at boot |
systemd-analyze verify myapp.service | Lint a unit file |
systemctl --user ... | Manage per-user services |
Journal (Logs)
| Command | Description |
|---|---|
journalctl -u service | Logs for a service |
journalctl -u service -f | Follow logs |
journalctl -u service --since "1 hour ago" | Recent logs |
journalctl -u service --since today | Today's logs |
journalctl -p err | Error-level and above |
journalctl --disk-usage | Journal disk usage |
journalctl --vacuum-size=500M | Limit journal to 500MB |
journalctl -b / -b -1 | This boot / previous boot (needs persistent journal) |
journalctl -k | Kernel messages (like dmesg) |
journalctl -u service -n 100 --no-pager | Last 100 lines, no pager (for scripts) |
journalctl -u service -o json-pretty | Structured output with all fields |
journalctl --since "2026-11-09 10:00" --until "2026-11-09 11:00" | Time window |
journalctl _PID=1234 | Filter by any journal field |
Unit File Template
# /etc/systemd/system/myapp.service
[Unit]
Description=My Application
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=app
Group=app
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/server
ExecReload=/bin/kill -HUP $MAINPID
Restart=always
RestartSec=5
Environment=NODE_ENV=production
EnvironmentFile=/opt/myapp/.env
LimitNOFILE=65535
# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/myapp/data
[Install]
WantedBy=multi-user.target
Wants= alone does not order anything; you need After=network-online.target too, or the service may start before the network is up. Use Type=notify if the app calls sd_notify, Type=exec to fail fast when the binary is missing.
Timer (cron replacement)
# /etc/systemd/system/backup.timer (runs backup.service)
[Unit]
Description=Nightly backup
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true # run at boot if the machine was off at 02:00
RandomizedDelaySec=10m
[Install]
WantedBy=timers.target
systemctl enable --now backup.timer
systemd-analyze calendar "*-*-* 02:00:00" # check when it fires next
Text Processing Pipeline
# Count HTTP status codes from access log
cat access.log | awk '{print $9}' | sort | uniq -c | sort -rn
# Find top 10 IP addresses
cat access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -10
# Extract unique errors
grep "ERROR" app.log | awk -F']' '{print $NF}' | sort -u
# Sum a numeric column
awk '{sum += $3} END {print sum}' data.txt
# Replace text in multiple files
find . -name "*.conf" -exec sed -i 's/old/new/g' {} +
# Watch a log file for a pattern
tail -f app.log | grep --line-buffered "ERROR"
# Monitor file changes
watch -n 2 'ls -la /var/log/app.log'
# Print lines 10-20
sed -n '10,20p' file
# Field by delimiter, print columns 1 and 3
awk -F: '{print $1, $3}' /etc/passwd
# Lines in file1 that are not in file2 (both sorted)
comm -23 <(sort file1) <(sort file2)
# Follow a rotated log by name (re-opens after logrotate)
tail -F /var/log/app.log
# Run a command on many inputs in parallel (4 at a time)
cat hosts.txt | xargs -P 4 -I{} ssh {} uptime
TIP
sed -i differs between GNU and BSD/macOS: on macOS use sed -i '' 's/a/b/' file. sed -i.bak works on both and keeps a backup.
User Management
| Command | Description |
|---|---|
useradd -m -s /bin/bash user | Create user with home dir |
userdel -r user | Delete user and home dir |
usermod -aG group user | Add user to group |
passwd user | Set password |
groups user | Show user's groups |
id user | Show UID, GID, groups |
su - user | Switch user |
sudo cmd | Run as root |
visudo | Edit sudoers safely |
visudo -f /etc/sudoers.d/deploy | Edit a sudoers drop-in safely |
sudo -l | What can I run with sudo? |
sudo -u app cmd | Run as another user |
sudo -i | Root login shell |
chage -l user | Password ageing info |
last / lastb | Recent logins / failed logins |
who / w | Who is logged in and what they run |
System Information
| Command | Description |
|---|---|
uname -a | Kernel and OS info |
cat /etc/os-release | Distribution info |
uptime | System uptime and load |
free -h | Memory usage |
nproc | Number of CPU cores |
lscpu | CPU details |
dmesg | tail | Kernel messages |
cat /proc/meminfo | Detailed memory info |
cat /proc/cpuinfo | CPU info |
vmstat 1 | Virtual memory stats (every 1s) |
iostat -x 1 | IO stats (every 1s) |
sar -u 1 10 | CPU usage (10 samples, 1s interval) |
hostnamectl | Hostname, OS, kernel, virtualization |
timedatectl | Time, time zone, NTP sync status |
lspci / lsusb | Hardware devices |
pidstat 1 | Per-process CPU every second (sysstat) |
ulimit -a | Resource limits of the current shell |
sysctl -a | grep somaxconn | Kernel parameters (set persistently in /etc/sysctl.d/*.conf) |
free -h: look at available, not free. Linux uses spare RAM for page cache (buff/cache), which is released on demand. uptime load average counts runnable and uninterruptible (I/O-blocked) tasks, so compare it with nproc.
Troubleshooting Quick Fixes
| Problem | Command |
|---|---|
| High CPU | top, htop, sort by CPU |
| High memory | ps aux --sort=-%mem | head -10 |
| Disk full | du -h --max-depth=1 / | sort -rh | head |
| Cannot connect to port | ss -tlnp | grep :PORT |
| DNS not resolving | cat /etc/resolv.conf, dig domain |
| Permission denied | ls -la file, check owner/group/permissions |
| Service won't start | systemctl status service, journalctl -u service |
| High IO wait | iostat -x 1, iotop |
| Too many open files | ulimit -n, lsof -p PID | wc -l |
| OOM killer | dmesg | grep -i oom, journalctl -k | grep oom |
Disk full but du disagrees | lsof +L1 (deleted-but-open files), df -i (inodes) |
| "Address already in use" | ss -tlnp 'sport = :8080' |
| Clock skew (TLS / token errors) | timedatectl, chronyc tracking |
| Boot is slow | systemd-analyze blame, systemd-analyze critical-chain |
Test Yourself
-
What command shows listening TCP ports with process IDs?
ss -tlnp -
How do you create nested directories in one command?
mkdir -p a/b/c -
What is the numeric permission for a file readable/writable by owner only?
600 -
How do you find files larger than 100MB?
find / -type f -size +100M -
What signal number is SIGKILL?
9 -
How do you set up SSH local port forwarding from local 8080 to remote 3000?
ssh -L 8080:localhost:3000 user@host -
What command shows disk usage of top-level directories in human-readable format?
du -h --max-depth=1 / -
How do you check the status of a systemd service and see recent logs?
systemctl status service -
What command generates an Ed25519 SSH key?
ssh-keygen -t ed25519 -C "email@example.com" -
How do you follow a log file in real time and filter for a pattern?
tail -f app.log | grep --line-buffered "ERROR"
Common Gotchas
rm -rfwith empty variables or a misplaced space. GNUrmrefuses a literal/(--preserve-rootis the default), butrm -rf "$DIR"/*with an unset$DIRexpands to/*, which is not protected, andrm -rf ~ /tmp/build(meant~/tmp/build) deletes your home directory. Use"${DIR:?}"in scripts so an empty variable aborts, and double-check paths.chmod 777on anything. This gives everyone full access. Use the minimum permissions needed (644 for files, 755 for directories).- Editing
/etc/sudoersdirectly. Always usevisudo-- it validates syntax. A broken sudoers file locks you out ofsudoentirely. - Forgetting
nohupfor long-running SSH commands. Without it, closing the SSH session kills the process. Usenohup cmd &ortmux/screen. pkill -f patternmatching more than you think.-fmatches the full command line, including your own shell orsudowrapper. Check withpgrep -af patternfirst.- Editing
/etc/fstaband rebooting untested. A typo can drop the box into emergency mode. Runmount -a(andfindmnt --verify) first; addnofailfor non-essential disks. systemctl restartafter editing a unit withoutdaemon-reload. systemd keeps using the old unit and warns that it changed on disk.- Firewall changes over SSH. A wrong rule locks you out. Allow port 22 first, and use
ufw/firewalldor a timed rollback (iptables-apply).
One-Liner Summary
Linux is the operating system that runs the internet -- learn file permissions, process management, ss/systemctl/journalctl, and you can troubleshoot any server.