Quick Reference
Cheatsheets
Commands I use daily. No fluff.
Search results
Official docs
Setup and Config
git config --global user.name "Name"Set your name for all repos
git config --global user.email "email@example.com"Set your email for all repos
git config --global core.editor vimSet default editor
git config --global init.defaultBranch mainSet default branch name to main
git config --global pull.rebase trueRebase by default on pull
git config --global alias.co checkoutCreate a shortcut alias
git config --list --show-originShow all config values and where they come from
git config --global credential.helper cacheCache credentials in memory temporarily
git config --global core.autocrlf inputFix line endings on commit (Mac/Linux)
git config --global diff.tool vscode && git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE'Set VS Code as default diff tool
Basics
git initInitialize a new repo in current directory
git clone <url>Clone a remote repo locally
git clone --depth 1 <url>Shallow clone, only latest commit
git add <file>Stage a specific file
git add -pInteractively stage chunks of changes
git commit -m "message"Commit staged changes with a message
git commit --amendEdit the last commit message or add staged changes to it
git statusShow working tree status
git status -sShort format status output
git diffShow unstaged changes
git diff --stagedShow staged changes
git diff <branch1>..<branch2>Compare two branches
Branching
git branchList local branches
git branch -aList all branches including remote
git branch <name>Create a new branch
git branch -d <name>Delete a merged branch
git branch -D <name>Force delete a branch regardless of merge status
git branch -m <old> <new>Rename a branch
git switch <branch>Switch to a branch
git switch -c <branch>Create and switch to a new branch
git checkout -b <branch>Create and switch to a new branch (old syntax)
git branch --mergedList branches already merged into current
git branch -vvShow branches with tracking info and last commit
Merging and Rebasing
git merge <branch>Merge branch into current branch
git merge --no-ff <branch>Merge with a merge commit even if fast-forward is possible
git merge --squash <branch>Squash all commits from branch into one staged change
git merge --abortAbort a merge in progress
git rebase <branch>Rebase current branch onto another
git rebase -i HEAD~3Interactive rebase last 3 commits
git rebase --onto main feature bugfixRebase bugfix onto main, detaching from feature
git rebase --abortAbort a rebase in progress
git rebase --continueContinue rebase after resolving conflicts
git config --global rerere.enabled trueEnable automatic reuse of recorded conflict resolutions
Stashing
git stashStash uncommitted changes
git stash -uStash including untracked files
git stash push -m "description"Stash with a descriptive message
git stash listList all stashes
git stash popApply latest stash and remove it from list
git stash apply stash@{2}Apply a specific stash without removing it
git stash drop stash@{0}Delete a specific stash
git stash clearDelete all stashes
git stash show -pShow the diff of latest stash
git stash branch <name>Create a branch from a stash
Remote
git remote -vList remotes with URLs
git remote add origin <url>Add a remote
git remote remove <name>Remove a remote
git remote rename origin upstreamRename a remote
git fetchDownload objects and refs from remote
git fetch --pruneFetch and remove deleted remote branches locally
git pullFetch and merge remote changes
git pull --rebaseFetch and rebase instead of merge
git pushPush commits to remote
git push -u origin <branch>Push and set upstream tracking
git push origin --delete <branch>Delete a remote branch
git push --force-with-leaseForce push but fail if remote has new commits
Undoing Changes
git restore <file>Discard unstaged changes in a file
git restore --staged <file>Unstage a file without losing changes
git reset HEAD~1Undo last commit, keep changes in working directory (unstaged)
git reset --soft HEAD~1Undo last commit, keep changes staged
git reset --hard HEAD~1Undo last commit and discard all changes (DESTRUCTIVE, no undo)
git reset --hard origin/mainReset branch to match remote exactly (DESTRUCTIVE, loses local commits)
git revert <commit>Create a new commit that undoes a specific commit
git revert HEAD --no-editRevert last commit without editing message
git clean -fdRemove untracked files and directories (DESTRUCTIVE, no undo)
git clean -fdnDry run, show what would be removed
git checkout -- .Discard all unstaged changes (old syntax)
Logging and History
git log --onelineCompact one-line log
git log --oneline --graph --allVisual branch graph of all branches
git log -n 5Show last 5 commits
git log --author="Name"Filter commits by author
git log --since="2 weeks ago"Show commits from last 2 weeks
git log -p <file>Show commit history with diffs for a file
git log --grep="fix"Search commit messages
git reflogShow history of HEAD changes, useful for recovery
git blame <file>Show who changed each line and when
git show <commit>Show details and diff of a specific commit
git shortlog -snCommit count per author, sorted
Tags
git tagList all tags
git tag v1.0.0Create a lightweight tag
git tag -a v1.0.0 -m "Release 1.0"Create an annotated tag with message
git tag -a v1.0.0 <commit>Tag a specific commit
git tag -d v1.0.0Delete a local tag
git push origin v1.0.0Push a specific tag to remote
git push origin --tagsPush all tags to remote
git push origin --delete v1.0.0Delete a remote tag
git describe --tagsShow most recent tag reachable from current commit
git tag -l "v1.*"List tags matching a pattern
Advanced
git cherry-pick <commit>Apply a commit from another branch
git cherry-pick --no-commit <commit>Apply changes without committing
git bisect startStart binary search for a buggy commit
git bisect good <commit>Mark a commit as good during bisect
git bisect bad <commit>Mark a commit as bad during bisect
git bisect resetEnd bisect session
git worktree add ../hotfix hotfix-branchCheck out a branch in a separate directory
git worktree listList all worktrees
git submodule add <url> <path>Add a submodule
git submodule update --init --recursiveInitialize and update all submodules
git archive --format=zip HEAD > archive.zipExport repo as a zip file
git rev-parse --short HEADGet current short commit hash (useful in CI/scripts)
git clean -fdxClean untracked AND ignored files (DESTRUCTIVE, full reset for CI)
git commit --fixup <commit>Create a fixup commit for later autosquash rebase
git rebase -i --autosquash HEAD~5Interactive rebase that auto-orders fixup commits
git log --all --full-history -- <file>Track a file through renames and deletions
Common Pipelines
git branch --merged | grep -v '\*\|main\|master' | xargs git branch -dDelete all local branches already merged into current
git log --all --oneline --graph --decoratePretty visual history of all branches
git diff --name-only HEAD~5..HEADList files changed in last 5 commits
git log --format='%an' | sort | uniq -c | sort -rnRank contributors by commit count
git log --diff-filter=D --summary | grep 'delete mode'Find all deleted files in history
git stash list | while read s; do echo "$s"; git stash show "$(echo $s | cut -d: -f1)"; echo; doneShow contents of all stashes
git log --oneline --since='last monday' --author="$(git config user.name)"Your commits since last Monday (standup helper)
git for-each-ref --sort=-committerdate refs/heads/ --format='%(committerdate:short) %(refname:short)'List branches sorted by last commit date
git log -S 'functionName' --onelineFind commits that added or removed a string (pickaxe)
git diff HEAD~1 --statShow file change stats for last commit
git remote prune origin && git branch -vv | grep 'gone]' | awk '{print $1}' | xargs git branch -dClean up local branches whose remote was deleted
git log --pretty=format:'%h %ad %s' --date=short --all -- <file>Full history of a specific file with short dates
Official docs
Navigation and Filesystem
cd <dir>Change directory
cd -Go back to previous directory
cd ~Go to home directory
pwdPrint current working directory
ls -laList all files with details including hidden
ls -lhList files with human-readable sizes
ls -ltList files sorted by modification time
tree -L 2Show directory tree 2 levels deep
du -sh <dir>Show total size of a directory
stat <file>Show detailed file metadata
File Operations
cp <src> <dst>Copy a file
cp -r <src> <dst>Copy a directory recursively
mv <src> <dst>Move or rename a file
rm <file>Remove a file
rm -rf <dir>Force remove a directory and its contents (DESTRUCTIVE, no trash)
mkdir -p path/to/dirCreate nested directories
touch <file>Create an empty file or update its timestamp
ln -s <target> <link>Create a symbolic link
rsync -avz <src> <dst>Sync files with progress, preserving attributes
rsync -avz --delete <src> <dst>Sync and remove files not in source
file <file>Determine file type
basename /path/to/file.txtExtract filename from path
Text Processing
grep -r "pattern" .Search recursively in current directory
grep -rn "pattern" --include="*.ts"Search with line numbers in specific file types
grep -i "pattern" <file>Case-insensitive search
grep -v "pattern" <file>Show lines that do NOT match
sed 's/old/new/g' <file>Replace all occurrences in a file (prints to stdout)
sed -i 's/old/new/g' <file>In-place replacement
awk '{print $1, $3}' <file>Print 1st and 3rd columns
awk -F: '{print $1}' /etc/passwdPrint first field with custom delimiter
cut -d',' -f1,3 <file>Extract 1st and 3rd columns from CSV
sort <file> | uniq -c | sort -rnCount occurrences and sort by frequency
wc -l <file>Count lines in a file
tr '[:lower:]' '[:upper:]' < <file>Convert to uppercase
File Viewing
cat <file>Print entire file contents
cat -n <file>Print file with line numbers
less <file>View file with scrolling
head -n 20 <file>Show first 20 lines
tail -n 20 <file>Show last 20 lines
tail -f <file>Follow file changes in real time
tail -f <file> | grep "error"Follow file and filter for errors
diff <file1> <file2>Show differences between two files
diff -u <file1> <file2>Unified diff format
column -t -s',' <file>Display CSV as aligned table
Permissions
chmod 755 <file>Set rwx for owner, rx for group and others
chmod 644 <file>Set rw for owner, read-only for group and others
chmod +x <file>Make a file executable
chmod -R 755 <dir>Recursively set permissions on a directory
chown user:group <file>Change owner and group
chown -R user:group <dir>Recursively change owner and group
chgrp <group> <file>Change group ownership
umask 022Set default permissions for new files
ls -la <file>Check current permissions on a file
idShow current user, UID, and groups
Process Management
ps auxList all running processes
ps aux | grep <name>Find a process by name
topReal-time process monitor
htopBetter interactive process monitor
kill <pid>Send SIGTERM to a process
kill -9 <pid>Force kill a process (no cleanup, use SIGTERM first)
killall <name>Kill all processes by name
jobsList background jobs in current shell
bg %1Resume job 1 in background
fg %1Bring job 1 to foreground
nohup <command> &Run command that survives terminal close
lsof -i :3000Find what process is using port 3000
System Monitoring
df -hShow disk space usage of all mounted filesystems
df -h /Show disk space of root partition only
df -iShow inode usage (can fill up even with disk space left)
du -sh *Show size of each item in current directory
du -sh * | sort -rh | head -10Top 10 largest items in current directory
du -d 1 -h /var/log | sort -rhShow sizes of subdirectories one level deep
ncdu /Interactive disk usage browser
free -hShow RAM usage (total, used, free, available)
free -h -s 5Show RAM usage refreshing every 5 seconds
cat /proc/meminfoDetailed memory breakdown
cat /proc/cpuinfo | grep 'model name' | head -1CPU model name
nprocNumber of CPU cores
lscpuDetailed CPU architecture info
uptimeHow long the system has been running and load averages
wWho is logged in and what they are doing
last rebootShow reboot history
lsblkList all block devices (disks, partitions)
fdisk -lList disk partitions with sizes (needs sudo)
iostat -x 1 5Disk I/O stats every second for 5 iterations
vmstat 1 5Virtual memory stats every second for 5 iterations
sar -u 1 5CPU usage every second for 5 iterations
dmesg | tail -20Last 20 kernel messages
cat /etc/os-releaseShow Linux distro and version
uname -aKernel version and system architecture
Archives and Compression
tar -czf archive.tar.gz <dir>Create gzipped tar archive
tar -xzf archive.tar.gzExtract gzipped tar archive
tar -xzf archive.tar.gz -C /target/dirExtract to a specific directory
tar -tf archive.tar.gzList contents without extracting
gzip <file>Compress file (replaces original)
gunzip <file>.gzDecompress gzipped file
zip -r archive.zip <dir>Create zip archive of a directory
unzip archive.zipExtract zip archive
unzip -l archive.zipList contents of zip without extracting
tar -cjf archive.tar.bz2 <dir>Create bzip2 compressed archive
Environment and Variables
export VAR="value"Set an environment variable
echo $VARPrint a variable value
envShow all environment variables
printenv PATHPrint a specific env variable
unset VARRemove an environment variable
source ~/.bashrcReload shell config
alias ll='ls -la'Create a command alias
aliasList all current aliases
unalias llRemove an alias
which <command>Show full path of a command
export PATH="$PATH:/new/path"Add directory to PATH
Redirection and Pipes
command > file.txtRedirect stdout to file (overwrite)
command >> file.txtAppend stdout to file
command 2> error.logRedirect stderr to file
command &> all.logRedirect both stdout and stderr to file
command 2>&1Redirect stderr to stdout
command1 | command2Pipe output of command1 to command2
command | tee file.txtPipe output and also write to file
command | xargs <other>Pass piped output as arguments
cat urls.txt | xargs -I {} curl -s {}Run curl for each line in file
command < input.txtFeed file as stdin to command
Search and Find
find . -name "*.log"Find files by name pattern
find . -type f -mtime -7Find files modified in last 7 days
find . -type f -size +100MFind files larger than 100MB
find . -name "*.tmp" -deleteFind and delete matching files
find . -type f -exec grep -l "pattern" {} +Find files containing a pattern
find . -empty -type fFind empty files
find . -type f -name "*.js" ! -path "*/node_modules/*"Find files excluding a directory
locate <filename>Fast file search using index database
whereis <command>Show binary, source, and man page paths
type <command>Show how a command is resolved (alias, builtin, file)
Service Management (systemd)
systemctl status <service>Check if a service is running
systemctl start <service>Start a service
systemctl stop <service>Stop a service
systemctl restart <service>Restart a service
systemctl reload <service>Reload config without full restart
systemctl enable <service>Start service automatically on boot
systemctl disable <service>Prevent service from starting on boot
systemctl enable --now <service>Enable and start in one command
systemctl list-units --type=service --state=runningList all running services
systemctl list-units --type=service --state=failedList all failed services
systemctl is-active <service>Check if active (returns exit code too)
systemctl is-enabled <service>Check if enabled on boot
systemctl daemon-reloadReload unit files after editing them
systemctl mask <service>Completely prevent a service from starting
systemctl unmask <service>Undo a mask
systemctl cat <service>Show the unit file contents
systemctl edit <service> --forceCreate or edit a service override
systemctl list-timersShow all scheduled timers (cron replacement)
Journalctl (Logs)
journalctl -u <service>Show logs for a specific service
journalctl -u <service> -fFollow logs for a service in real time
journalctl -u <service> --since '1 hour ago'Logs from the last hour
journalctl -u <service> --since todayLogs since midnight
journalctl -u <service> -n 100Last 100 log lines for a service
journalctl -p errShow only error-level messages
journalctl -p warning..errShow warnings and errors
journalctl -kKernel messages only (like dmesg)
journalctl --disk-usageHow much disk space logs are using
journalctl --vacuum-size=500MShrink logs to 500MB
journalctl --vacuum-time=7dDelete logs older than 7 days
journalctl -bLogs from current boot only
journalctl -b -1Logs from previous boot
journalctl --no-pager -u <service> | grep errorPipe logs through grep without pager
Cron and Scheduling
crontab -lList your cron jobs
crontab -eEdit your cron jobs
crontab -l -u <user>List another user's cron jobs (needs sudo)
cat /etc/crontabView system-wide cron table
ls /etc/cron.d/List system cron job files
ls /etc/cron.daily/List daily cron scripts
* * * * * /path/to/script.shCron format: min hour day month weekday
0 */2 * * * /path/to/script.shRun every 2 hours
0 9 * * 1-5 /path/to/script.shRun at 9am on weekdays
at now + 30 minutesSchedule a one-time job 30 minutes from now
atqList pending at jobs
atrm <job-id>Remove a pending at job
User and Group Management
useradd -m -s /bin/bash <user>Create user with home directory and bash shell
usermod -aG sudo <user>Add user to sudo group
usermod -aG <group> <user>Add user to a group
userdel -r <user>Delete user and their home directory
passwd <user>Change a user's password
groups <user>Show what groups a user belongs to
getent passwd <user>Get user account details
visudoSafely edit the sudoers file
su - <user>Switch to another user with their environment
whoamiPrint current username
lastShow login history
faillog -aShow failed login attempts
Debugging and Tracing
strace -p <pid>Trace system calls of a running process
strace -c <command>Run command and summarize syscall stats
strace -e trace=network <command>Trace only network-related syscalls
ltrace <command>Trace library calls
lsof +D /pathFind processes using files in a directory
lsof -p <pid>List all files opened by a process
openssl s_client -connect <host>:443Debug TLS/SSL connection to a server
openssl x509 -in cert.pem -text -nooutRead details of an SSL certificate
md5sum <file>Generate MD5 checksum
sha256sum <file>Generate SHA-256 checksum
Common Pipelines
ps aux | sort -rnk 4 | head -10Top 10 processes by memory usage
ps aux | sort -rnk 3 | head -10Top 10 processes by CPU usage
find . -name '*.log' -mtime +30 -deleteDelete log files older than 30 days
find . -type f -name '*.js' | xargs wc -l | sort -n | tail -20Top 20 largest JS files by line count
du -sh */ | sort -rh | head -10Top 10 largest directories in current path
history | awk '{$1=""; print}' | sort | uniq -c | sort -rn | head -20Your 20 most used commands (full command strings)
curl -s https://api.example.com/data | jq '.items[] | {name, id}'Fetch JSON API and extract fields with jq
tail -f /var/log/syslog | grep --line-buffered 'error' | tee errors.logLive tail, filter errors, and save to file simultaneously
find . -name '*.md' -exec grep -l 'TODO' {} + | sortFind all markdown files containing TODO
cat access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -20Top 20 IPs hitting your server
for f in *.jpg; do convert "$f" -resize 800x "resized_$f"; doneBatch resize all JPGs in current directory
diff <(sort file1.txt) <(sort file2.txt)Compare two files after sorting both
watch -n 5 'df -h /'Monitor disk usage every 5 seconds
for f in *\ *; do mv "$f" "${f// /_}"; doneReplace spaces with underscores in all filenames
ss -tlnp | awk 'NR>1 {print $4}' | rev | cut -d: -f1 | rev | sort -n | uniqList all listening ports sorted numerically
jq (JSON Processing)
jq '.' <file>Pretty-print a JSON file
jq -r '.key' <file>Extract a top-level key (raw output, no quotes)
jq '.nested.key' <file>Access nested fields with dot notation
jq '.[0]' <file>Get the first element of a JSON array
jq '.[]' <file>Iterate over all array elements
jq '.[] | .name' <file>Extract a field from each array element
jq '[.[] | .name]' <file>Collect results back into an array
jq '.[] | {name, id}' <file>Build new objects from selected fields
jq '.[] | select(.age > 30)' <file>Filter array elements by condition
jq '.[] | select(.name == "foo")' <file>Filter by exact string match
jq '.[] | select(.name | test("^foo"))' <file>Filter using regex match
jq '.[] | select(.tags | contains(["urgent"]))' <file>Filter by array containing a value
jq 'map(select(.status == "active"))' <file>Map + filter in one step
jq 'map(.price * .quantity)' <file>Transform values with arithmetic
jq '[.[] | .amount] | add' <file>Sum all values of a field
jq '.items | length' <file>Count elements in an array
jq '.items | sort_by(.date)' <file>Sort array of objects by a field
jq '.items | sort_by(.date) | reverse' <file>Sort descending
jq '.items | group_by(.category)' <file>Group array elements by a field
jq '.items | unique_by(.id)' <file>Remove duplicates by a field
jq 'keys' <file>List all keys of an object
jq 'to_entries[] | "\(.key)=\(.value)"' <file>Convert object to key=value lines
jq 'from_entries' <file>Convert [{key,value}] array back to object
jq '.a + .b' <file>Merge two objects
jq '.items |= map(. + {processed: true})' <file>Update array in place, adding a field to each element
jq 'del(.unwanted)' <file>Remove a key from an object
jq '.[] | @csv' <file>Format output as CSV
jq '.[] | @tsv' <file>Format output as TSV
jq -r '.[] | [.name, .email] | @csv' <file>Extract specific fields as CSV
jq -s '.' *.jsonSlurp multiple files into a single array
jq -s 'add' file1.json file2.jsonMerge two JSON files (objects or arrays)
jq -n '{name: "foo", count: 42}'Generate JSON from scratch
jq --arg name "foo" '.[] | select(.name == $name)' <file>Pass shell variable into jq filter
jq -r '.results[] | "\(.id)\t\(.name)"' <file>Custom formatted output with string interpolation
jq 'if .status == "ok" then .data else empty end' <file>Conditional logic
jq '.value // "default"' <file>Alternative operator (fallback for null)
jq 'paths(scalars)' <file>List all leaf paths in a JSON document
jq '[paths(scalars) as $p | {path: ($p | join(".")), value: getpath($p)}]' <file>Flatten nested JSON to path-value pairs
curl -s <url> | jq '.data[] | {id, name}'Pipe API response into jq
jq -c '.[]' <file>Compact output (one JSON object per line, good for piping)
jq -e '.key' <file>Exit with error code if result is null or false
One-Liners
python3 -m http.server 8000Quick HTTP server in current directory
openssl rand -hex 32Generate a random 64-char hex string
date +%sCurrent Unix timestamp
date -d @1700000000Convert Unix timestamp to human date
echo 'SELECT 1' | xclip -selection clipboardCopy text to clipboard (Linux with xclip)
xclip -selection clipboard -o > file.txtPaste clipboard to file (Linux with xclip)
yes 'confirm' | head -5Generate repeated input (pipe to commands needing confirmation)
time <command>Measure how long a command takes
!! | xclip -selection clipboardRe-run last command and pipe its output to clipboard
curl -w '%{http_code}' -o /dev/null -s <url>Get just the HTTP status code from a URL
hostname -IShow all IP addresses of this machine
nc -zv <host> <port>Test if a TCP port is open on a host
Official docs
curl
curl -s <url>Fetch URL silently
curl -o <file> <url>Download URL to a file
curl -O <url>Download and keep original filename
curl -X POST -H "Content-Type: application/json" -d '{"key":"val"}' <url>POST JSON to an endpoint
curl -I <url>Fetch only response headers
curl -L <url>Follow redirects
curl -u user:pass <url>Basic auth request
curl -H "Authorization: Bearer <token>" <url>Request with bearer token
curl -w '%{http_code}' -o /dev/null -s <url>Get just the HTTP status code
curl -w '%{time_total}' -o /dev/null -s <url>Measure response time
curl -x http://proxy:8080 <url>Request through a proxy
curl -k https://<url>Skip SSL certificate verification
curl --retry 3 --retry-delay 5 <url>Retry failed request 3 times with 5s delay
wget <url>Download a file
wget -q <url>Download silently
wget -r -l 2 <url>Recursively download site 2 levels deep
wget -c <url>Resume a partially downloaded file
wget --mirror <url>Mirror an entire website
wget -i urls.txtDownload all URLs listed in a file
SSH and SCP
ssh user@hostConnect to remote host
ssh -p 2222 user@hostConnect on a custom port
ssh -i ~/.ssh/key.pem user@hostConnect with a specific key
ssh -L 8080:localhost:3000 user@hostLocal port forwarding (access remote 3000 on local 8080)
ssh -R 9090:localhost:3000 user@hostRemote port forwarding (expose local 3000 on remote 9090)
ssh -D 1080 user@hostSOCKS proxy through SSH tunnel
ssh -J jumphost user@targetConnect through a jump/bastion host
ssh-keygen -t ed25519 -C "email@example.com"Generate an SSH key (ed25519, recommended)
ssh-copy-id user@hostCopy your public key to a remote host
ssh-add ~/.ssh/keyAdd a key to the SSH agent
scp <file> user@host:/path/Copy file to remote host
scp -r user@host:/path/ .Copy directory from remote host
rsync -avz -e ssh <src> user@host:/dstSync over SSH with compression
DNS
dig <domain>Full DNS lookup
dig +short <domain>DNS lookup, IP only
dig MX <domain>Lookup mail servers
dig NS <domain>Lookup nameservers
dig TXT <domain>Lookup TXT records (SPF, DKIM, etc.)
dig @8.8.8.8 <domain>Query a specific DNS server
dig +trace <domain>Show full DNS resolution path
nslookup <domain>Simple DNS query
host <domain>Quick DNS lookup with less output
cat /etc/resolv.confShow configured DNS servers
resolvectl statusShow DNS resolver status (systemd)
Ports and Connections
ss -tlnpShow listening TCP ports with process names
ss -tunapShow all TCP/UDP connections with PIDs
ss -sSocket statistics summary
ss state established '( dport = :443 )'Show established HTTPS connections
netstat -tlnpShow listening TCP ports with PIDs (legacy)
lsof -i :8080Find what process is using port 8080
nc -zv <host> <port>Test if a TCP port is open
nc -zv <host> 1-1000Scan port range 1-1000
nc -l 8080Listen on a port (simple server)
IP and Routing
ip addr showShow all network interfaces and IPs
ip -4 addr showShow only IPv4 addresses
ip link showShow network interface status (up/down)
ip route showShow routing table
ip route get <ip>Show which route is used to reach an IP
ip neigh showShow ARP table (known neighbors)
hostname -IShow all IPs of this machine
hostname -fShow fully qualified domain name
ping -c 4 <host>Send 4 ping packets
traceroute <host>Show network path to host
mtr <host>Combined ping + traceroute (live updating)
Firewall (iptables/nftables)
iptables -L -n -vList all rules with packet counts
iptables -A INPUT -p tcp --dport 80 -j ACCEPTAllow incoming HTTP traffic
iptables -A INPUT -s <ip> -j DROPBlock traffic from a specific IP
iptables -D INPUT <rule-number>Delete a rule by number
iptables-save > rules.bakExport current rules
iptables-restore < rules.bakRestore rules from backup
ufw statusShow UFW firewall status (Ubuntu)
ufw allow 22/tcpAllow SSH through UFW
ufw deny from <ip>Block an IP with UFW
firewall-cmd --list-allShow firewalld rules (RHEL/CentOS)
firewall-cmd --add-port=8080/tcp --permanentOpen a port with firewalld
firewall-cmd --reloadReload firewalld rules
Packet Capture and Analysis
tcpdump -i eth0Capture all traffic on an interface
tcpdump -i eth0 port 80Capture only HTTP traffic
tcpdump -i eth0 host <ip>Capture traffic to/from a specific IP
tcpdump -i eth0 -w capture.pcapSave capture to file (open in Wireshark)
tcpdump -r capture.pcapRead a saved capture file
tcpdump -i eth0 -c 100Capture first 100 packets then stop
tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn) != 0'Capture only SYN packets (new connections)
nmap -sT <host>TCP connect scan
nmap -sT -p 1-65535 <host>Scan all TCP ports
nmap -sV <host>Detect service versions on open ports
nmap -O <host>Detect operating system
Official docs
Images
docker imagesList all local images
docker pull <image>:<tag>Download an image from registry
docker build -t <name>:<tag> .Build image from Dockerfile in current directory
docker build -t <name>:<tag> -f Dockerfile.prod .Build with a specific Dockerfile
docker build --no-cache -t <name>:<tag> .Build without using cache
docker tag <image> <registry>/<name>:<tag>Tag an image for a registry
docker push <registry>/<name>:<tag>Push image to a registry
docker rmi <image>Remove an image
docker image pruneRemove dangling (untagged) images
docker image prune -aRemove all unused images (DESTRUCTIVE)
docker history <image>Show layers and commands that built an image
docker inspect <image>Show detailed image metadata as JSON
Containers
docker run -d --name <name> <image>Run container in background
docker run -it <image> /bin/bashRun container with interactive shell
docker run -d -p 8080:80 <image>Run with port mapping (host:container)
docker run -d -v /host/path:/container/path <image>Run with volume mount
docker run -d --env-file .env <image>Run with environment variables from file
docker run -d --restart unless-stopped <image>Run with auto-restart policy
docker run --rm <image>Run and auto-remove when stopped
docker psList running containers
docker ps -aList all containers including stopped
docker stop <container>Stop a running container gracefully
docker start <container>Start a stopped container
docker restart <container>Restart a container
docker rm <container>Remove a stopped container
docker rm -f <container>Force remove a running container
docker rename <old> <new>Rename a container
Exec and Logs
docker exec -it <container> /bin/bashOpen a shell inside a running container
docker exec -it <container> shOpen shell (for Alpine/minimal images)
docker exec <container> <command>Run a one-off command in a container
docker logs <container>Show container logs
docker logs -f <container>Follow container logs in real time
docker logs --tail 100 <container>Show last 100 log lines
docker logs --since 1h <container>Show logs from last hour
docker logs -f <container> 2>&1 | grep errorFollow logs filtered for errors
docker cp <container>:/path/file .Copy file from container to host
docker cp file.txt <container>:/path/Copy file from host to container
docker top <container>Show running processes inside container
docker statsLive CPU/memory/IO stats for all containers
docker stats <container>Live stats for a specific container
Docker Compose
docker compose up -dStart all services in background
docker compose up -d --buildRebuild images and start
docker compose downStop and remove containers, networks
docker compose down -vStop and remove including volumes (DESTRUCTIVE)
docker compose psList running compose services
docker compose logs -f <service>Follow logs for a specific service
docker compose exec <service> /bin/bashShell into a running service
docker compose restart <service>Restart a specific service
docker compose pullPull latest images for all services
docker compose configValidate and display the resolved compose file
docker compose up -d --scale <service>=3Run 3 instances of a service
docker compose --profile debug up -dStart with a specific profile
Volumes
docker volume lsList all volumes
docker volume create <name>Create a named volume
docker volume inspect <name>Show volume details (mountpoint, driver)
docker volume rm <name>Remove a volume
docker volume pruneRemove all unused volumes (DESTRUCTIVE)
docker run -v <volume>:/data <image>Mount a named volume
docker run -v $(pwd):/app <image>Bind mount current directory
docker run --tmpfs /tmp <image>Mount a tmpfs (in-memory) filesystem
Networks
docker network lsList all networks
docker network create <name>Create a network
docker network create --driver overlay <name>Create overlay network (Swarm)
docker network inspect <name>Show network details and connected containers
docker network connect <network> <container>Connect a container to a network
docker network disconnect <network> <container>Disconnect a container from a network
docker network rm <name>Remove a network
docker network pruneRemove all unused networks
Cleanup
docker system dfShow Docker disk usage breakdown
docker system pruneRemove stopped containers, unused networks, dangling images
docker system prune -a --volumesNuclear cleanup: everything unused (DESTRUCTIVE)
docker container pruneRemove all stopped containers
docker image prune -aRemove all unused images
docker volume pruneRemove all unused volumes (DESTRUCTIVE)
docker ps -aq --filter status=exited | xargs docker rmRemove all exited containers
docker images -q --filter dangling=true | xargs docker rmiRemove all dangling images
Buildx (Multi-Platform)
docker buildx lsList all builders and their platforms
docker buildx create --name mybuilder --useCreate a new builder and set it as active
docker buildx use mybuilderSwitch to a specific builder
docker buildx inspect --bootstrapStart builder and show its details
docker buildx build --platform linux/amd64,linux/arm64 -t <name>:<tag> .Build for multiple platforms
docker buildx build --platform linux/amd64,linux/arm64 -t <name>:<tag> --push .Build multi-platform and push to registry
docker buildx build --load -t <name>:<tag> .Build and load into local Docker (single platform only)
docker buildx build --cache-from type=registry,ref=<image>:cache -t <name>:<tag> .Build using remote cache
docker buildx build --cache-to type=registry,ref=<image>:cache,mode=max .Build and export cache to registry
docker buildx build --output type=local,dest=./out .Export build output to local directory
docker buildx build --secret id=mysecret,src=secret.txt .Pass a secret file to the build
docker buildx build --ssh default .Forward SSH agent to the build
docker buildx build --progress=plain .Show full build output without collapsing steps
docker buildx rm mybuilderRemove a builder
docker buildx pruneRemove build cache
docker buildx bakeBuild from a bake file (docker-bake.hcl or docker-bake.json)
docker buildx bake --printShow resolved bake configuration without building
docker buildx imagetools inspect <image>:<tag>Show manifest and platform details of a remote image
Debugging
docker inspect <container>Full container metadata as JSON
docker inspect -f '{{.State.Status}}' <container>Get just the container status
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container>Get container IP address
docker diff <container>Show filesystem changes in a container
docker eventsStream real-time Docker daemon events
docker port <container>Show port mappings for a container
docker wait <container>Block until container stops, then print exit code
docker commit <container> <image>:<tag>Create image from a container's current state