Skip to content
Unverified — AI-generated content. Help verify 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

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
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)
which commandFind command path

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

bash
# 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

chown Commands

bash
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
bash
chmod 4755 file    # SUID
chmod 2755 dir     # SGID
chmod 1755 /tmp    # Sticky bit

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

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
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

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

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

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)

Port & Connection Debugging

bash
# 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
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)

bash
# 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
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Save rules (Debian/Ubuntu)
iptables-save > /etc/iptables/rules.v4

SSH

bash
# 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

# 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

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

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

Unit File Template

ini
# /etc/systemd/system/myapp.service
[Unit]
Description=My Application
After=network.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

Text Processing Pipeline

bash
# 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'

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

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)

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

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 a misplaced space. rm -rf / tmp deletes root, not /tmp. Always double-check paths, especially with variables.
  • 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.

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.

"What I cannot create, I do not understand." — Richard Feynman