⏳
Loading cheatsheet...
File commands, process management, networking, text processing, security, package managers — Linux CLI mastery.
| Flag | Description |
|---|---|
| -l | Long format (permissions, owner, size, date) |
| -a | Show hidden files (dotfiles) |
| -h | Human-readable sizes (K, M, G) |
| -R | Recursive listing |
| -t | Sort by modification time (newest first) |
| -S | Sort by file size (largest first) |
| -r | Reverse sort order |
| -1 | One file per line |
| -F | Append type indicator (*/, @, |) |
| --color=auto | Color-coded output |
| -G | Disable colors |
| ls -lhS | Long format, human sizes, sort by size |
| ls -lhat | Long format, hidden, time sorted |
| Command | Description |
|---|---|
| cp -r src/ dst/ | Copy directory recursively |
| cp -a src/ dst/ | Archive (preserve all attributes) |
| cp -p file dst/ | Preserve mode, ownership, timestamps |
| cp -u src/ dst/ | Copy only newer files (update) |
| cp -v src/ dst/ | Verbose (show files copied) |
| cp -i file dst/ | Prompt before overwrite |
| mv -i src dst/ | Interactive (prompt before overwrite) |
| mv -n src dst/ | No-clobber (don't overwrite) |
| mv -v src dst/ | Verbose |
| rm -r dir/ | Remove directory and contents |
| rm -f file | Force remove (ignore nonexistent) |
| rm -i file | Interactive (prompt each file) |
| rm -rf dir/ | Force recursive (use with caution!) |
| rm -ri dir/ | Interactive recursive (safest) |
| Example | Description |
|---|---|
| find . -name "*.js" | Find by name (glob pattern) |
| find . -iname "*.JS" | Case-insensitive name search |
| find . -type f | Find files only |
| find . -type d | Find directories only |
| find . -size +100M | Files larger than 100MB |
| find . -size -1k | Files smaller than 1KB |
| find . -mtime -7 | Modified in last 7 days |
| find . -atime +30 | Not accessed in 30+ days |
| find . -perm 755 | Files with exact permissions |
| find . -perm -u+x | Files executable by owner |
| find . -empty | Empty files and directories |
| find . -user john | Files owned by john |
| find . -newer file.txt | Files newer than file.txt |
| find . -exec rm {} \; | Delete all found files |
| find . -exec ls -la {} + | Batch exec with ls |
| Command | Description |
|---|---|
| xargs -I {} cmd {} | Replace {} with each arg |
| xargs -n 1 cmd | One arg per command invocation |
| xargs -P 4 cmd | Run 4 commands in parallel |
| xargs -0 | Null-delimited input (with find -print0) |
| ln -s target link | Create symbolic link |
| ln target link | Create hard link |
| stat file.txt | Detailed file metadata |
| file * | Detect file types |
| tree -L 2 | Directory tree (2 levels) |
| tree -a -I "node_modules" | Show all, ignore pattern |
| basename /a/b/c.txt | Extract filename: c.txt |
| dirname /a/b/c.txt | Extract directory: /a/b |
| realpath symlink | Resolve to actual path |
| readlink -f symlink | Get canonical path |
| du -sh * | Disk usage per item (human) |
# Advanced find + xargs examples
# Find and delete .log files older than 30 days
find /var/log -name "*.log" -mtime +30 -exec rm {} \;
# Find all .js files and count lines
find . -name "*.js" -exec wc -l {} + | tail -1
# Find and move files matching pattern
find . -name "*.tmp" -exec mv {} /tmp/trash/ \;
# Safe xargs with spaces in filenames
find . -name "*.jpg" -print0 | xargs -0 -I {} cp {} /backup/
# Find files and open in vim
find . -name "*.py" -exec vim {} +| Command | Description |
|---|---|
| ps aux | All processes (BSD format) |
| ps -ef | All processes (System V format) |
| ps -eo pid,ppid,cmd | Custom columns |
| ps -eo pid,pcpu,pmem,cmd | PID, CPU%, MEM%, command |
| ps -e --forest | Tree view of processes |
| ps -u username | Processes for specific user |
| ps -p 1234 | Info about specific PID |
| ps -Lp 1234 | Show threads for PID |
| ps aux --sort=-%mem | Sort by memory (top) |
| ps aux --sort=-%cpu | Sort by CPU (top) |
| ps aux | grep -v grep | grep app | Filter processes |
| ps -eo pid,tid,class,rtprio,ni,cmd | Real-time priorities |
| Key | Action (in top) |
|---|---|
| M | Sort by memory usage |
| P | Sort by CPU usage (default) |
| N | Sort by PID |
| T | Sort by time/cumulative time |
| c | Toggle command name vs full command |
| 1 | Toggle showing all CPUs |
| k | Kill a process (prompts PID) |
| r | Renice a process |
| z | Toggle color mode |
| h / ? | Help screen |
| q | Quit |
| Space | Force update |
| d + N | Change refresh delay to N seconds |
| htop -s PERCENT_CPU | Start htop sorted by CPU |
| htop -p 1234,5678 | Monitor specific PIDs |
| Signal | Number | Description |
|---|---|---|
| SIGTERM | 15 | Graceful termination (default) |
| SIGKILL | 9 | Force kill (cannot be caught) |
| SIGHUP | 1 | Hangup (reload config common) |
| SIGINT | 2 | Interrupt (Ctrl+C) |
| SIGQUIT | 3 | Quit with core dump |
| SIGUSR1 | 10 | User-defined signal 1 |
| SIGUSR2 | 12 | User-defined signal 2 |
| SIGSTOP | 19 | Stop/suspend process |
| SIGCONT | 18 | Continue stopped process |
| SIGPIPE | 13 | Broken pipe |
| SIGALRM | 14 | Alarm timer expired |
| SIGSEGV | 11 | Segmentation fault |
| kill -9 PID | Force kill (SIGKILL) | |
| killall -9 nginx | Kill all by name | |
| pkill -f "pattern" | Kill by pattern match |
| Command | Description |
|---|---|
| command & | Run in background |
| bg %1 | Resume suspended job in bg |
| fg %1 | Bring job to foreground |
| jobs | List background jobs |
| jobs -l | Jobs with PIDs |
| nohup cmd & | Run immune to hangup |
| disown -h %1 | Detach job from shell |
| nice -n 10 cmd | Run with reduced priority (10) |
| nice -n -5 cmd | Run with increased priority (-5) |
| renice -n 5 -p PID | Change priority of running proc |
| ionice -c2 -n7 cmd | Set I/O scheduling class |
| Ctrl+Z | Suspend current process |
| wait %1 | Wait for background job to finish |
| pgrep -af nginx | Find PIDs matching pattern |
| pstree -p PID | Show process tree |
kill -15 PID (or just kill PID) before resorting to kill -9. SIGTERM allows the process to clean up resources, flush buffers, and close connections gracefully. SIGKILL cannot be caught or handled.| Flag | Description |
|---|---|
| -X POST | HTTP POST method |
| -H "Content-Type: app/json" | Set request header |
| -d '{"key":"val"}' | POST data (implies -X POST) |
| -d @file.json | POST data from file |
| -u user:pass | Basic authentication |
| -b "cookie=value" | Send cookie |
| -c cookies.txt | Save cookies to file |
| -o output.html | Write output to file |
| -O | Save with remote filename |
| -L | Follow redirects |
| -s | Silent mode (no progress) |
| -v | Verbose (show headers) |
| -i | Include response headers |
| -I / --head | HEAD request only |
| -w "%{http_code}" | Output format string |
| -x proxy:8080 | Use HTTP proxy |
| -k / --insecure | Skip SSL verification |
| --compressed | Request compressed response |
| --limit-rate 1M | Throttle download speed |
| -T file.txt | Upload file (PUT) |
| -F "file=@f.jpg" | Multipart form upload |
| Option | Description |
|---|---|
| -p 2222 user@host | Connect on custom port |
| -i ~/.ssh/key.pem | Use specific identity file |
| -L 8080:localhost:80 | Local port forwarding |
| -R 8080:localhost:80 | Remote port forwarding |
| -D 1080 | Dynamic (SOCKS) proxy |
| -J jump_host | Proxy jump through host |
| -A | Enable agent forwarding |
| -v | Verbose (debug connection) |
| -vvv | Very verbose debug |
| -C | Enable compression |
| -N | No remote command (port fwd only) |
| -f | Go to background after auth |
| -o StrictHostKeyChecking=no | Skip host key check |
| -o ConnectTimeout=10 | Connection timeout |
| ssh-copy-id user@host | Copy public key to host |
| ssh-keygen -t ed25519 | Generate new SSH key |
| Command | Description |
|---|---|
| scp file user@host:/path | Copy file to remote |
| scp -r dir/ user@host:/path | Copy directory recursively |
| scp user@host:/path . | Copy from remote to local |
| scp -P 2222 file host:/path | Custom port |
| wget URL | Download file |
| wget -c URL | Continue partial download |
| wget -q URL | Quiet download |
| wget -O out.html URL | Output filename |
| wget -r -np URL | Recursive download (no parent) |
| rsync -avz src/ dst/ | Archive, verbose, compress |
| rsync -avz --delete src/ dst/ | Mirror (delete extras) |
| rsync -avz --progress src/ dst/ | Show progress |
| rsync -e ssh -avz src/ dst/ | Over SSH |
| rsync --exclude="*.log" src/ dst/ | Exclude pattern |
| Command | Description |
|---|---|
| ss -tlnp | TCP listening ports with process |
| ss -tunlp | TCP + UDP listening ports |
| ss -s | Socket statistics summary |
| ss -tnp | grep :8080 | Connections to port 8080 |
| netstat -tlnp | TCP listening (legacy) |
| lsof -i :80 | Processes using port 80 |
| lsof -i tcp | All TCP connections |
| lsof -u username | Files open by user |
| lsof +D /dir | All open files in directory |
| dig example.com | DNS lookup |
| dig example.com MX | Mail exchange records |
| dig +short example.com | Short answer (IP only) |
| nslookup example.com | Simple DNS lookup |
| host example.com | DNS lookup (simpler) |
| traceroute example.com | Packet route trace |
| nmap -sP 192.168.1.0/24 | Ping scan subnet |
| nmap -sV localhost | Service version detection |
| Command | Description |
|---|---|
| ip addr show | List all network interfaces |
| ip addr add 192.168.1.10/24 dev eth0 | Add IP address |
| ip addr del 192.168.1.10/24 dev eth0 | Delete IP address |
| ip link show | List network interfaces |
| ip link set eth0 up/down | Enable/disable interface |
| ip link set eth0 promisc on | Enable promiscuous mode |
| ip route show | Show routing table |
| ip route add default via 192.168.1.1 | Add default gateway |
| ip route add 10.0.0.0/24 via 192.168.1.1 | Add route |
| ip route del 10.0.0.0/24 | Delete route |
| ip neigh show | ARP table (neighbors) |
| ip -s link show eth0 | Interface statistics |
| ip -br addr | Brief address listing |
| Command | Description |
|---|---|
| nmap hostname | Basic port scan (top 1000) |
| nmap -p 80,443 host | Scan specific ports |
| nmap -p 1-65535 host | Scan all ports |
| nmap -sV host | Service version detection |
| nmap -O host | OS detection |
| nmap -sP 192.168.1.0/24 | Ping scan (host discovery) |
| nmap -A host | Aggressive (OS + version + script) |
| nmap -sU host | UDP scan |
| nmap -sn 192.168.1.0/24 | No port scan, just hosts |
| nmap --script=vuln host | Vulnerability scan |
# Practical network debugging
# Check what is listening on a port
ss -tlnp | grep :3000
# Test API endpoint with curl
curl -s -o /dev/null -w "HTTP %{http_code} in %{time_total}s\n" https://api.example.com
# SSH tunnel (access remote DB locally)
ssh -L 5432:localhost:5432 user@db-server
# Jump through bastion host
ssh -J bastion user@internal-server
# Download with resume capability
wget -c --progress=bar:force https://large-file.zip| Command | Description |
|---|---|
| df -h | Disk space (human-readable) |
| df -Th | With filesystem type |
| df -i | Inode usage |
| du -sh * | Dir sizes (human, summary) |
| du -sh dir/ | Total size of directory |
| du -h --max-depth=1 | One level deep sizes |
| du -ah dir/ | All files with sizes |
| fdisk -l | List disk partitions |
| lsblk | List block devices |
| blkid | Block device attributes (UUID) |
| mount /dev/sdb1 /mnt | Mount partition |
| umount /mnt | Unmount |
| smartctl -a /dev/sda | S.M.A.R.T. disk health |
| ncdu /path | Interactive disk usage analyzer |
| Command | Description |
|---|---|
| free -h | Memory usage (human) |
| free -m | Memory in megabytes |
| free -g | Memory in gigabytes |
| free -h -s 2 | Refresh every 2 seconds |
| free -h --total | Show total row |
| vmstat 1 5 | Virtual memory stats (5 samples) |
| vmstat -s | Memory event counters |
| /proc/meminfo | Detailed memory info (file) |
| top -o %MEM | Sort by memory (top) |
| ps aux --sort=-rss | head | Top memory consumers |
| ps -eo pid,ppid,rss,cmd --sort=-rss | All procs by RSS |
| pmap -x PID | Memory map of process |
| smem -rs pss | Proportional memory usage |
du measures actual file sizes on disk, while df measures filesystem-level free space. Deleted files still held open by processes show in df but not du. Use lsof +L1 to find deleted files still in use.| Flag / Example | Description |
|---|---|
| -E (egrep) | Extended regex (ERE) |
| -P | Perl-compatible regex (PCRE) |
| -i | Case insensitive |
| -v | Invert match |
| -r / -R | Recursive (follow symlinks w/ -R) |
| -l | Only show matching filenames |
| -n | Show line numbers |
| -c | Count matches per file |
| -o | Only show matched part |
| -A 2 | 2 lines After match |
| -B 2 | 2 lines Before match |
| -C 2 | 2 lines Context (before+after) |
| -e "a" -e "b" | Multiple patterns (OR) |
| -f patterns.txt | Patterns from file |
| --include="*.js" | Only search .js files |
| --exclude-dir=node_modules | Exclude directory |
| -P "\d{3}-\d{4}" | Perl regex with backreferences |
| Command | Description |
|---|---|
| sed "s/old/new/" | Replace first occurrence per line |
| sed "s/old/new/g" | Replace all occurrences |
| sed "s/old/new/gi" | Replace all, case insensitive |
| sed "s/old/new/2" | Replace only 2nd occurrence |
| sed "2d" | Delete line 2 |
| sed "2,5d" | Delete lines 2 through 5 |
| sed "/pattern/d" | Delete lines matching pattern |
| sed -n "10,20p" | Print lines 10-20 |
| sed "/start/,/end/p" | Print range between patterns |
| sed "s/.*/PREFIX &/" | Add prefix to each line |
| sed -i.bak "s/a/b/g" | In-place with backup |
| sed "y/abc/xyz/" | Transliterate characters |
| sed "s/^/ /" | Indent all lines |
| sed "/^$/d" | Delete blank lines |
| sed -i "1i\header" file | Insert line at top |
| Example | Description |
|---|---|
| awk '{print $1}' | Print first field |
| awk -F: '{print $1}' /etc/passwd | Colon-delimited fields |
| awk 'NR==10 {print}' | Print line 10 |
| awk '/error/ {count++} END {print count}' | Count matches |
| awk '{sum+=$1} END {print sum/NR}' | Average of column 1 |
| awk 'NR==FNR {a[$1]; next} $1 in a' | Join two files |
| awk 'length($0)>80' | Lines longer than 80 chars |
| awk '{print NR, $0}' | Line numbers with content |
| awk 'BEGIN{OFS=","} {print $1,$2}' | Output field separator |
| awk '{gsub(/old/,"new"); print}' | Global substitution |
| awk '{printf "%-15s %5d\n",$1,$2}' | Formatted print |
| awk 'NF{print}' | Print non-empty lines |
| awk '{$1=$1};1' | Strip leading/trailing whitespace |
| awk '{print toupper($0)}' | Convert to uppercase |
| Command | Description |
|---|---|
| cut -d: -f1 /etc/passwd | Extract field 1 (colon delim) |
| cut -c1-10 file | Extract characters 1-10 |
| cut -d, -f2,4 file.csv | Extract fields 2 and 4 |
| tr a-z A-Z | Translate lowercase to uppercase |
| tr -d '\n' | Delete all newlines |
| tr -s " " | Squeeze/reduce repeated spaces |
| sort -n | Numeric sort |
| sort -k2 -n | Sort by 2nd field numerically |
| sort -rn | Reverse numeric sort |
| sort -u | Unique lines (sorted) |
| sort -t, -k3,3 | CSV sort by column 3 |
| uniq -c | Count consecutive duplicates |
| uniq -d | Show only duplicates |
| uniq -u | Show only unique lines |
| wc -l | Count lines |
| wc -w | Count words |
| wc -c | Count characters |
| diff -u file1 file2 | Unified diff format |
| diff -u file1 file2 | patch -p1 | Apply patch |
| comm file1 file2 | Compare sorted files (3 cols) |
# Power text processing pipelines
# Find top 10 most common words in a file
cat file.txt | tr -s ' ' '\n' | sort | uniq -c | sort -rn | head -10
# Extract all emails from files
grep -rhoE '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' . | sort -u
# Sum a column of numbers
awk '{sum+=$1} END {print "Total:", sum}' numbers.txt
# Replace all IPs in files (in-place)
find . -name "*.conf" -exec sed -i 's/10\.0\.0\.1/192\.168\.1.1/g' {} +| Octal | Permission | Meaning |
|---|---|---|
| 0 | --- | No permissions |
| 1 | --x | Execute only |
| 2 | -w- | Write only |
| 3 | -wx | Write + Execute |
| 4 | r-- | Read only |
| 5 | r-x | Read + Execute |
| 6 | rw- | Read + Write |
| 7 | rwx | Read + Write + Execute |
| 755 | rwxr-xr-x | Standard (files/scripts) |
| 644 | rw-r--r-- | Standard (documents) |
| 700 | rwx------ | Private (scripts) |
| 600 | rw------- | Private (files/keys) |
| 400 | r-------- | Read-only (certificates) |
| Command | Description |
|---|---|
| chown user:group file | Change owner and group |
| chgrp group file | Change group only |
| umask 022 | Default permissions (no write for others) |
| umask 077 | Private (no perms for group/others) |
| chmod +x script.sh | Make executable |
| chmod g+s dir/ | Set group ID bit (inherit group) |
| chmod +t dir/ | Sticky bit (only owner can delete) |
| chmod u+s file | Setuid (run as owner) |
| iptables -L | List firewall rules |
| iptables -A INPUT -p tcp --dport 22 -j ACCEPT | Allow SSH |
| iptables -A INPUT -j DROP | Drop all other input |
| getfacl file | View ACL permissions |
| setfacl -m u:user:rw file | Set ACL for user |
| sudo -l | List allowed sudo commands |
| Command | Description |
|---|---|
| apt update | Refresh package lists |
| apt upgrade | Upgrade all packages |
| apt install pkg | Install package |
| apt remove pkg | Remove package (keep config) |
| apt purge pkg | Remove + config files |
| apt search term | Search packages |
| apt show pkg | Package details |
| apt list --installed | List installed |
| apt autoremove | Remove unused dependencies |
| apt-cache policy pkg | Show version/priority |
| apt-mark hold pkg | Prevent upgrade of package |
| Command | Description |
|---|---|
| dnf check-update | Check for updates |
| dnf update | Update all packages |
| dnf install pkg | Install package |
| dnf remove pkg | Remove package |
| dnf search term | Search packages |
| dnf info pkg | Package information |
| dnf list installed | List installed |
| dnf autoremove | Remove unused deps |
| dnf history | Transaction history |
| dnf clean all | Clean cache |
| Command | Description |
|---|---|
| pacman -Syu | Sync DB and upgrade all |
| pacman -S pkg | Install package |
| pacman -R pkg | Remove package |
| pacman -Rs pkg | Remove + unused deps |
| pacman -Ss term | Search packages |
| pacman -Qi pkg | Package info (installed) |
| pacman -Si pkg | Package info (repo) |
| pacman -Q | List all installed |
| pacman -Qe | List explicitly installed |
| pacman -Qt | List orphans |
| pacman -Sc | Clean package cache |
| yay -S pkg | AUR package (community) |
| Command | Description |
|---|---|
| brew update | Update Homebrew & formulae |
| brew upgrade | Upgrade all packages |
| brew install pkg | Install formula |
| brew uninstall pkg | Uninstall formula |
| brew search term | Search formulae |
| brew info pkg | Package information |
| brew list | List installed formulae |
| brew cleanup | Remove old versions |
| brew doctor | Check for issues |
| brew tap repo | Add third-party tap |
| brew install --cask app | Install macOS app |
grep -rn "pattern" (recursive search), find . -name "*.log" -mtime +7 -delete (find and clean old logs), ss -tlnp (check listening ports), curl -s -o /dev/null -w '%{http_code}' (quick health check), and df -h (disk space).