On this page

Linux Cheat Sheet

Quick reference for essential Linux commands, file permissions, process management, networking, and systemd.


File System

CommandDescription
pwdPrint working directory
ls -laList all files with details
ls -lahHuman-readable file sizes
ls -ltSort by modification time
ls -lSSort by file size
cd -Go to previous directory
cd ~Go to home directory
tree -L 2Directory tree, 2 levels deep

File Operations

CommandDescription
cp file destCopy file
cp -r dir destCopy directory recursively
mv old newMove or rename
rm fileDelete file
rm -rf dirDelete directory recursively
mkdir -p a/b/cCreate nested directories
touch fileCreate file or update timestamp
ln -s target linkCreate symbolic link
stat fileDetailed 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 /targetExtract into a directory
tar -tzf out.tar.gzList archive contents
file nameDetect file type
realpath fileAbsolute path, symlinks resolved

File Content

CommandDescription
cat filePrint entire file
less filePaginated viewer
head -n 20 fileFirst 20 lines
tail -n 20 fileLast 20 lines
tail -f fileFollow file (live logs)
wc -l fileCount lines
sort fileSort lines
uniqRemove adjacent duplicates
sort file | uniq -cCount occurrences
cut -d',' -f1,3 fileExtract CSV columns 1 and 3
tr 'a-z' 'A-Z'Translate characters
diff file1 file2Compare files
md5sum fileMD5 checksum
sha256sum fileSHA-256 checksum
CommandDescription
find / -name "*.log"Find files by name
find / -type f -size +100MFind files larger than 100MB
find / -mtime -7Modified 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" -deleteFind and delete
find . -type f -print0 | xargs -0 grep -l fooSafe with spaces in filenames
grep -r "pattern" /pathSearch recursively
grep -rn "pattern" /pathSearch with line numbers
grep -ri "pattern" /pathCase-insensitive
grep -rl "pattern" /pathList matching files only
grep -v "pattern"Invert match
grep -E "regex" fileExtended regex
locate filenameFast search (uses db; plocate on modern distros, refresh with updatedb)
which commandFind command path
command -v cmdPOSIX way to find a command (also sees aliases/functions)
type cmdShow 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

SymbolNumericMeaning
r4Read
w2Write
x1Execute
-0No permission

Common Permission Patterns

NumericSymbolicUse Case
644-rw-r--r--Regular files
755-rwxr-xr-xExecutables, directories
600-rw-------Private files (SSH keys)
700-rwx------Private directories
660-rw-rw----Group-shared files
775-rwxrwxr-xGroup-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

PermissionNumericEffect
SUID4xxxExecute as file owner
SGID2xxxExecute as file group / inherit group in dir
Sticky1xxxOnly 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

CommandDescription
ps auxAll processes with details
ps aux --sort=-%memSort by memory usage
ps aux --sort=-%cpuSort by CPU usage
ps -ef --forestProcess tree
topInteractive process monitor
htopBetter interactive monitor
pgrep -f "pattern"Find PID by name/pattern
pidof nginxFind PID by exact name
ps -o pid,ppid,stat,etime,cmd -p PIDChosen columns for one process
pstree -pProcess tree with PIDs
lsof -p PIDFiles and sockets a process has open
strace -p PID -f -e trace=networkTrace syscalls of a running process
ls -l /proc/PID/cwd /proc/PID/exeWorking dir and binary of a process
cat /proc/PID/statusMemory (VmRSS), threads, state

Managing Processes

CommandDescription
kill PIDGraceful kill (SIGTERM)
kill -9 PIDForce kill (SIGKILL)
kill -HUP PIDReload config (SIGHUP)
killall nameKill all by name
pkill -f "pattern"Kill by pattern
nohup cmd &Run in background, survive logout
disown -h %1Detach an already-running job from the shell
systemd-run --user --unit=job cmdRun as a transient systemd unit (logs in journal)
nice -n 10 cmd / renice -n 10 -p PIDLower CPU priority
timeout 30s cmdKill command after 30 seconds
cmd &Run in background
jobsList background jobs
fg %1Bring job 1 to foreground
bg %1Resume stopped job in background
Ctrl+ZSuspend current process
Ctrl+CInterrupt current process

Signals

SignalNumberMeaning
SIGHUP1Hangup / reload
SIGINT2Interrupt (Ctrl+C)
SIGQUIT3Quit with core dump
SIGKILL9Force kill (cannot catch)
SIGTERM15Graceful termination
SIGSTOP19Pause (cannot catch)
SIGCONT18Resume
SIGTSTP20Terminal stop (Ctrl+Z, can be caught)
SIGUSR1 / SIGUSR210 / 12App-defined (e.g. reopen logs)
SIGPIPE13Wrote 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

CommandDescription
df -hDisk space by filesystem
du -sh dir/Directory size
du -h --max-depth=1 /Size of top-level directories
du -ah dir/ | sort -rh | head -20Largest files in directory
lsblkBlock device list
mountShow mounted filesystems
fdisk -lList disk partitions
ncdu /Interactive disk usage (if installed)
ionice -c 3 cmdRun command with low IO priority
df -iInode usage ("No space left" with free bytes = inodes exhausted)
df -hTDisk space with filesystem type
findmntMount tree (clearer than mount)
lsblk -fBlock devices with filesystems and UUIDs
blkidUUIDs and labels (for /etc/fstab)
lsof +L1Deleted files still held open (space not freed until process restarts)
mount -aMount everything in /etc/fstab (test fstab edits before reboot)

Networking

Network Information

CommandDescription
ip addr showShow IP addresses
ip route showShow routing table
ss -tlnpListening TCP ports with PIDs
ss -ulnpListening UDP ports
ss -sSocket statistics summary
netstat -tlnpListening ports (legacy)
hostname -IShow all IP addresses
cat /etc/resolv.confDNS configuration
ip link showNetwork interfaces
ip -br aBrief: one line per interface with IPs
ip route get 8.8.8.8Which interface/gateway a destination uses
ss -tanp state establishedEstablished TCP connections with processes
ss -tn dst :443Connections to port 443
resolvectl statusDNS servers when systemd-resolved manages /etc/resolv.conf
ip neighARP / neighbour table

Connectivity Testing

CommandDescription
ping -c 4 hostICMP ping (4 packets)
traceroute hostTrace packet route
mtr hostCombines ping and traceroute
curl -I urlHTTP headers only
curl -v urlVerbose HTTP request
curl -o /dev/null -w "%{http_code}" urlJust status code
wget -q -O - urlDownload to stdout
dig domainDNS lookup
dig +short domainDNS lookup (short)
nslookup domainDNS lookup (simpler)
host domainDNS lookup (simplest)
dig @1.1.1.1 domain AAAAQuery a specific server / record type
dig +trace domainFollow delegation from the root
getent hosts domainResolve like applications do (honours /etc/hosts, nsswitch)
curl --resolve example.com:443:1.2.3.4 https://example.comTest a host against a specific IP
openssl s_client -connect host:443 -servername hostInspect TLS handshake and cert
tcpdump -i any -nn port 443Capture 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

CommandDescription
systemctl start serviceStart service
systemctl stop serviceStop service
systemctl restart serviceRestart service
systemctl reload serviceReload config without restart
systemctl status serviceService status and recent logs
systemctl enable serviceStart on boot
systemctl disable serviceDo not start on boot
systemctl is-active serviceCheck if running
systemctl is-enabled serviceCheck if enabled
systemctl list-units --type=serviceList all services
systemctl list-units --failedList failed services
systemctl daemon-reloadReload unit files after changes
systemctl enable --now serviceEnable and start in one step
systemctl edit serviceCreate a drop-in override (/etc/systemd/system/service.d/override.conf)
systemctl cat serviceShow the unit file plus all drop-ins
systemctl show service -p Restart,MemoryMaxShow effective properties
systemctl list-timersScheduled timers (systemd's cron)
systemctl mask serviceMake a service impossible to start
systemctl reset-failedClear failed state
systemd-analyze blameSlowest units at boot
systemd-analyze verify myapp.serviceLint a unit file
systemctl --user ...Manage per-user services

Journal (Logs)

CommandDescription
journalctl -u serviceLogs for a service
journalctl -u service -fFollow logs
journalctl -u service --since "1 hour ago"Recent logs
journalctl -u service --since todayToday's logs
journalctl -p errError-level and above
journalctl --disk-usageJournal disk usage
journalctl --vacuum-size=500MLimit journal to 500MB
journalctl -b / -b -1This boot / previous boot (needs persistent journal)
journalctl -kKernel messages (like dmesg)
journalctl -u service -n 100 --no-pagerLast 100 lines, no pager (for scripts)
journalctl -u service -o json-prettyStructured output with all fields
journalctl --since "2026-11-09 10:00" --until "2026-11-09 11:00"Time window
journalctl _PID=1234Filter 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

CommandDescription
useradd -m -s /bin/bash userCreate user with home dir
userdel -r userDelete user and home dir
usermod -aG group userAdd user to group
passwd userSet password
groups userShow user's groups
id userShow UID, GID, groups
su - userSwitch user
sudo cmdRun as root
visudoEdit sudoers safely
visudo -f /etc/sudoers.d/deployEdit a sudoers drop-in safely
sudo -lWhat can I run with sudo?
sudo -u app cmdRun as another user
sudo -iRoot login shell
chage -l userPassword ageing info
last / lastbRecent logins / failed logins
who / wWho is logged in and what they run

System Information

CommandDescription
uname -aKernel and OS info
cat /etc/os-releaseDistribution info
uptimeSystem uptime and load
free -hMemory usage
nprocNumber of CPU cores
lscpuCPU details
dmesg | tailKernel messages
cat /proc/meminfoDetailed memory info
cat /proc/cpuinfoCPU info
vmstat 1Virtual memory stats (every 1s)
iostat -x 1IO stats (every 1s)
sar -u 1 10CPU usage (10 samples, 1s interval)
hostnamectlHostname, OS, kernel, virtualization
timedatectlTime, time zone, NTP sync status
lspci / lsusbHardware devices
pidstat 1Per-process CPU every second (sysstat)
ulimit -aResource limits of the current shell
sysctl -a | grep somaxconnKernel 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

ProblemCommand
High CPUtop, htop, sort by CPU
High memoryps aux --sort=-%mem | head -10
Disk fulldu -h --max-depth=1 / | sort -rh | head
Cannot connect to portss -tlnp | grep :PORT
DNS not resolvingcat /etc/resolv.conf, dig domain
Permission deniedls -la file, check owner/group/permissions
Service won't startsystemctl status service, journalctl -u service
High IO waitiostat -x 1, iotop
Too many open filesulimit -n, lsof -p PID | wc -l
OOM killerdmesg | grep -i oom, journalctl -k | grep oom
Disk full but du disagreeslsof +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 slowsystemd-analyze blame, systemd-analyze critical-chain

Test Yourself
  1. What command shows listening TCP ports with process IDs? ss -tlnp

  2. How do you create nested directories in one command? mkdir -p a/b/c

  3. What is the numeric permission for a file readable/writable by owner only? 600

  4. How do you find files larger than 100MB? find / -type f -size +100M

  5. What signal number is SIGKILL? 9

  6. How do you set up SSH local port forwarding from local 8080 to remote 3000? ssh -L 8080:localhost:3000 user@host

  7. What command shows disk usage of top-level directories in human-readable format? du -h --max-depth=1 /

  8. How do you check the status of a systemd service and see recent logs? systemctl status service

  9. What command generates an Ed25519 SSH key? ssh-keygen -t ed25519 -C "email@example.com"

  10. 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 -rf with empty variables or a misplaced space. GNU rm refuses a literal / (--preserve-root is the default), but rm -rf "$DIR"/* with an unset $DIR expands to /*, which is not protected, and rm -rf ~ /tmp/build (meant ~/tmp/build) deletes your home directory. Use "${DIR:?}" in scripts so an empty variable aborts, and double-check paths.
  • chmod 777 on anything. This gives everyone full access. Use the minimum permissions needed (644 for files, 755 for directories).
  • Editing /etc/sudoers directly. Always use visudo -- it validates syntax. A broken sudoers file locks you out of sudo entirely.
  • Forgetting nohup for long-running SSH commands. Without it, closing the SSH session kills the process. Use nohup cmd & or tmux/screen.
  • pkill -f pattern matching more than you think. -f matches the full command line, including your own shell or sudo wrapper. Check with pgrep -af pattern first.
  • Editing /etc/fstab and rebooting untested. A typo can drop the box into emergency mode. Run mount -a (and findmnt --verify) first; add nofail for non-essential disks.
  • systemctl restart after editing a unit without daemon-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/firewalld or 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.