Skip to main content

Quick Reference

Cheatsheets

Commands I use daily. No fluff.

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 vim
Set default editor
git config --global init.defaultBranch main
Set default branch name to main
git config --global pull.rebase true
Rebase by default on pull
git config --global alias.co checkout
Create a shortcut alias
git config --list --show-origin
Show all config values and where they come from
git config --global credential.helper cache
Cache credentials in memory temporarily
git config --global core.autocrlf input
Fix 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 init
Initialize 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 -p
Interactively stage chunks of changes
git commit -m "message"
Commit staged changes with a message
git commit --amend
Edit the last commit message or add staged changes to it
git status
Show working tree status
git status -s
Short format status output
git diff
Show unstaged changes
git diff --staged
Show staged changes
git diff <branch1>..<branch2>
Compare two branches

Branching

git branch
List local branches
git branch -a
List 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 --merged
List branches already merged into current
git branch -vv
Show 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 --abort
Abort a merge in progress
git rebase <branch>
Rebase current branch onto another
git rebase -i HEAD~3
Interactive rebase last 3 commits
git rebase --onto main feature bugfix
Rebase bugfix onto main, detaching from feature
git rebase --abort
Abort a rebase in progress
git rebase --continue
Continue rebase after resolving conflicts
git config --global rerere.enabled true
Enable automatic reuse of recorded conflict resolutions

Stashing

git stash
Stash uncommitted changes
git stash -u
Stash including untracked files
git stash push -m "description"
Stash with a descriptive message
git stash list
List all stashes
git stash pop
Apply 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 clear
Delete all stashes
git stash show -p
Show the diff of latest stash
git stash branch <name>
Create a branch from a stash

Remote

git remote -v
List remotes with URLs
git remote add origin <url>
Add a remote
git remote remove <name>
Remove a remote
git remote rename origin upstream
Rename a remote
git fetch
Download objects and refs from remote
git fetch --prune
Fetch and remove deleted remote branches locally
git pull
Fetch and merge remote changes
git pull --rebase
Fetch and rebase instead of merge
git push
Push 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-lease
Force 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~1
Undo last commit, keep changes in working directory (unstaged)
git reset --soft HEAD~1
Undo last commit, keep changes staged
git reset --hard HEAD~1
Undo last commit and discard all changes (DESTRUCTIVE, no undo)
git reset --hard origin/main
Reset 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-edit
Revert last commit without editing message
git clean -fd
Remove untracked files and directories (DESTRUCTIVE, no undo)
git clean -fdn
Dry run, show what would be removed
git checkout -- .
Discard all unstaged changes (old syntax)

Logging and History

git log --oneline
Compact one-line log
git log --oneline --graph --all
Visual branch graph of all branches
git log -n 5
Show 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 reflog
Show 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 -sn
Commit count per author, sorted

Tags

git tag
List all tags
git tag v1.0.0
Create 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.0
Delete a local tag
git push origin v1.0.0
Push a specific tag to remote
git push origin --tags
Push all tags to remote
git push origin --delete v1.0.0
Delete a remote tag
git describe --tags
Show 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 start
Start 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 reset
End bisect session
git worktree add ../hotfix hotfix-branch
Check out a branch in a separate directory
git worktree list
List all worktrees
git submodule add <url> <path>
Add a submodule
git submodule update --init --recursive
Initialize and update all submodules
git archive --format=zip HEAD > archive.zip
Export repo as a zip file
git rev-parse --short HEAD
Get current short commit hash (useful in CI/scripts)
git clean -fdx
Clean 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~5
Interactive 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 -d
Delete all local branches already merged into current
git log --all --oneline --graph --decorate
Pretty visual history of all branches
git diff --name-only HEAD~5..HEAD
List files changed in last 5 commits
git log --format='%an' | sort | uniq -c | sort -rn
Rank 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; done
Show 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' --oneline
Find commits that added or removed a string (pickaxe)
git diff HEAD~1 --stat
Show file change stats for last commit
git remote prune origin && git branch -vv | grep 'gone]' | awk '{print $1}' | xargs git branch -d
Clean 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

Navigation and Filesystem

cd <dir>
Change directory
cd -
Go back to previous directory
cd ~
Go to home directory
pwd
Print current working directory
ls -la
List all files with details including hidden
ls -lh
List files with human-readable sizes
ls -lt
List files sorted by modification time
tree -L 2
Show 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/dir
Create 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.txt
Extract 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/passwd
Print first field with custom delimiter
cut -d',' -f1,3 <file>
Extract 1st and 3rd columns from CSV
sort <file> | uniq -c | sort -rn
Count 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 022
Set default permissions for new files
ls -la <file>
Check current permissions on a file
id
Show current user, UID, and groups

Process Management

ps aux
List all running processes
ps aux | grep <name>
Find a process by name
top
Real-time process monitor
htop
Better 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
jobs
List background jobs in current shell
bg %1
Resume job 1 in background
fg %1
Bring job 1 to foreground
nohup <command> &
Run command that survives terminal close
lsof -i :3000
Find what process is using port 3000

System Monitoring

df -h
Show disk space usage of all mounted filesystems
df -h /
Show disk space of root partition only
df -i
Show 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 -10
Top 10 largest items in current directory
du -d 1 -h /var/log | sort -rh
Show sizes of subdirectories one level deep
ncdu /
Interactive disk usage browser
free -h
Show RAM usage (total, used, free, available)
free -h -s 5
Show RAM usage refreshing every 5 seconds
cat /proc/meminfo
Detailed memory breakdown
cat /proc/cpuinfo | grep 'model name' | head -1
CPU model name
nproc
Number of CPU cores
lscpu
Detailed CPU architecture info
uptime
How long the system has been running and load averages
w
Who is logged in and what they are doing
last reboot
Show reboot history
lsblk
List all block devices (disks, partitions)
fdisk -l
List disk partitions with sizes (needs sudo)
iostat -x 1 5
Disk I/O stats every second for 5 iterations
vmstat 1 5
Virtual memory stats every second for 5 iterations
sar -u 1 5
CPU usage every second for 5 iterations
dmesg | tail -20
Last 20 kernel messages
cat /etc/os-release
Show Linux distro and version
uname -a
Kernel version and system architecture

Archives and Compression

tar -czf archive.tar.gz <dir>
Create gzipped tar archive
tar -xzf archive.tar.gz
Extract gzipped tar archive
tar -xzf archive.tar.gz -C /target/dir
Extract to a specific directory
tar -tf archive.tar.gz
List contents without extracting
gzip <file>
Compress file (replaces original)
gunzip <file>.gz
Decompress gzipped file
zip -r archive.zip <dir>
Create zip archive of a directory
unzip archive.zip
Extract zip archive
unzip -l archive.zip
List 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 $VAR
Print a variable value
env
Show all environment variables
printenv PATH
Print a specific env variable
unset VAR
Remove an environment variable
source ~/.bashrc
Reload shell config
alias ll='ls -la'
Create a command alias
alias
List all current aliases
unalias ll
Remove an alias
which <command>
Show full path of a command
export PATH="$PATH:/new/path"
Add directory to PATH

Redirection and Pipes

command > file.txt
Redirect stdout to file (overwrite)
command >> file.txt
Append stdout to file
command 2> error.log
Redirect stderr to file
command &> all.log
Redirect both stdout and stderr to file
command 2>&1
Redirect stderr to stdout
command1 | command2
Pipe output of command1 to command2
command | tee file.txt
Pipe 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.txt
Feed file as stdin to command

Search and Find

find . -name "*.log"
Find files by name pattern
find . -type f -mtime -7
Find files modified in last 7 days
find . -type f -size +100M
Find files larger than 100MB
find . -name "*.tmp" -delete
Find and delete matching files
find . -type f -exec grep -l "pattern" {} +
Find files containing a pattern
find . -empty -type f
Find 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=running
List all running services
systemctl list-units --type=service --state=failed
List 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-reload
Reload 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> --force
Create or edit a service override
systemctl list-timers
Show all scheduled timers (cron replacement)

Journalctl (Logs)

journalctl -u <service>
Show logs for a specific service
journalctl -u <service> -f
Follow logs for a service in real time
journalctl -u <service> --since '1 hour ago'
Logs from the last hour
journalctl -u <service> --since today
Logs since midnight
journalctl -u <service> -n 100
Last 100 log lines for a service
journalctl -p err
Show only error-level messages
journalctl -p warning..err
Show warnings and errors
journalctl -k
Kernel messages only (like dmesg)
journalctl --disk-usage
How much disk space logs are using
journalctl --vacuum-size=500M
Shrink logs to 500MB
journalctl --vacuum-time=7d
Delete logs older than 7 days
journalctl -b
Logs from current boot only
journalctl -b -1
Logs from previous boot
journalctl --no-pager -u <service> | grep error
Pipe logs through grep without pager

Cron and Scheduling

crontab -l
List your cron jobs
crontab -e
Edit your cron jobs
crontab -l -u <user>
List another user's cron jobs (needs sudo)
cat /etc/crontab
View system-wide cron table
ls /etc/cron.d/
List system cron job files
ls /etc/cron.daily/
List daily cron scripts
* * * * * /path/to/script.sh
Cron format: min hour day month weekday
0 */2 * * * /path/to/script.sh
Run every 2 hours
0 9 * * 1-5 /path/to/script.sh
Run at 9am on weekdays
at now + 30 minutes
Schedule a one-time job 30 minutes from now
atq
List 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
visudo
Safely edit the sudoers file
su - <user>
Switch to another user with their environment
whoami
Print current username
last
Show login history
faillog -a
Show 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 /path
Find processes using files in a directory
lsof -p <pid>
List all files opened by a process
openssl s_client -connect <host>:443
Debug TLS/SSL connection to a server
openssl x509 -in cert.pem -text -noout
Read details of an SSL certificate
md5sum <file>
Generate MD5 checksum
sha256sum <file>
Generate SHA-256 checksum

Common Pipelines

ps aux | sort -rnk 4 | head -10
Top 10 processes by memory usage
ps aux | sort -rnk 3 | head -10
Top 10 processes by CPU usage
find . -name '*.log' -mtime +30 -delete
Delete log files older than 30 days
find . -type f -name '*.js' | xargs wc -l | sort -n | tail -20
Top 20 largest JS files by line count
du -sh */ | sort -rh | head -10
Top 10 largest directories in current path
history | awk '{$1=""; print}' | sort | uniq -c | sort -rn | head -20
Your 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.log
Live tail, filter errors, and save to file simultaneously
find . -name '*.md' -exec grep -l 'TODO' {} + | sort
Find all markdown files containing TODO
cat access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -20
Top 20 IPs hitting your server
for f in *.jpg; do convert "$f" -resize 800x "resized_$f"; done
Batch 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// /_}"; done
Replace spaces with underscores in all filenames
ss -tlnp | awk 'NR>1 {print $4}' | rev | cut -d: -f1 | rev | sort -n | uniq
List 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 '.' *.json
Slurp multiple files into a single array
jq -s 'add' file1.json file2.json
Merge 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 8000
Quick HTTP server in current directory
openssl rand -hex 32
Generate a random 64-char hex string
date +%s
Current Unix timestamp
date -d @1700000000
Convert Unix timestamp to human date
echo 'SELECT 1' | xclip -selection clipboard
Copy text to clipboard (Linux with xclip)
xclip -selection clipboard -o > file.txt
Paste clipboard to file (Linux with xclip)
yes 'confirm' | head -5
Generate repeated input (pipe to commands needing confirmation)
time <command>
Measure how long a command takes
!! | xclip -selection clipboard
Re-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 -I
Show all IP addresses of this machine
nc -zv <host> <port>
Test if a TCP port is open on a host

Networking

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.txt
Download all URLs listed in a file

SSH and SCP

ssh user@host
Connect to remote host
ssh -p 2222 user@host
Connect on a custom port
ssh -i ~/.ssh/key.pem user@host
Connect with a specific key
ssh -L 8080:localhost:3000 user@host
Local port forwarding (access remote 3000 on local 8080)
ssh -R 9090:localhost:3000 user@host
Remote port forwarding (expose local 3000 on remote 9090)
ssh -D 1080 user@host
SOCKS proxy through SSH tunnel
ssh -J jumphost user@target
Connect through a jump/bastion host
ssh-keygen -t ed25519 -C "email@example.com"
Generate an SSH key (ed25519, recommended)
ssh-copy-id user@host
Copy your public key to a remote host
ssh-add ~/.ssh/key
Add 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:/dst
Sync 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.conf
Show configured DNS servers
resolvectl status
Show DNS resolver status (systemd)

Ports and Connections

ss -tlnp
Show listening TCP ports with process names
ss -tunap
Show all TCP/UDP connections with PIDs
ss -s
Socket statistics summary
ss state established '( dport = :443 )'
Show established HTTPS connections
netstat -tlnp
Show listening TCP ports with PIDs (legacy)
lsof -i :8080
Find what process is using port 8080
nc -zv <host> <port>
Test if a TCP port is open
nc -zv <host> 1-1000
Scan port range 1-1000
nc -l 8080
Listen on a port (simple server)

IP and Routing

ip addr show
Show all network interfaces and IPs
ip -4 addr show
Show only IPv4 addresses
ip link show
Show network interface status (up/down)
ip route show
Show routing table
ip route get <ip>
Show which route is used to reach an IP
ip neigh show
Show ARP table (known neighbors)
hostname -I
Show all IPs of this machine
hostname -f
Show 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 -v
List all rules with packet counts
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
Allow incoming HTTP traffic
iptables -A INPUT -s <ip> -j DROP
Block traffic from a specific IP
iptables -D INPUT <rule-number>
Delete a rule by number
iptables-save > rules.bak
Export current rules
iptables-restore < rules.bak
Restore rules from backup
ufw status
Show UFW firewall status (Ubuntu)
ufw allow 22/tcp
Allow SSH through UFW
ufw deny from <ip>
Block an IP with UFW
firewall-cmd --list-all
Show firewalld rules (RHEL/CentOS)
firewall-cmd --add-port=8080/tcp --permanent
Open a port with firewalld
firewall-cmd --reload
Reload firewalld rules

Packet Capture and Analysis

tcpdump -i eth0
Capture all traffic on an interface
tcpdump -i eth0 port 80
Capture only HTTP traffic
tcpdump -i eth0 host <ip>
Capture traffic to/from a specific IP
tcpdump -i eth0 -w capture.pcap
Save capture to file (open in Wireshark)
tcpdump -r capture.pcap
Read a saved capture file
tcpdump -i eth0 -c 100
Capture 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

Images

docker images
List 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 prune
Remove dangling (untagged) images
docker image prune -a
Remove 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/bash
Run 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 ps
List running containers
docker ps -a
List 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/bash
Open a shell inside a running container
docker exec -it <container> sh
Open 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 error
Follow 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 stats
Live CPU/memory/IO stats for all containers
docker stats <container>
Live stats for a specific container

Docker Compose

docker compose up -d
Start all services in background
docker compose up -d --build
Rebuild images and start
docker compose down
Stop and remove containers, networks
docker compose down -v
Stop and remove including volumes (DESTRUCTIVE)
docker compose ps
List running compose services
docker compose logs -f <service>
Follow logs for a specific service
docker compose exec <service> /bin/bash
Shell into a running service
docker compose restart <service>
Restart a specific service
docker compose pull
Pull latest images for all services
docker compose config
Validate and display the resolved compose file
docker compose up -d --scale <service>=3
Run 3 instances of a service
docker compose --profile debug up -d
Start with a specific profile

Volumes

docker volume ls
List 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 prune
Remove 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 ls
List 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 prune
Remove all unused networks

Cleanup

docker system df
Show Docker disk usage breakdown
docker system prune
Remove stopped containers, unused networks, dangling images
docker system prune -a --volumes
Nuclear cleanup: everything unused (DESTRUCTIVE)
docker container prune
Remove all stopped containers
docker image prune -a
Remove all unused images
docker volume prune
Remove all unused volumes (DESTRUCTIVE)
docker ps -aq --filter status=exited | xargs docker rm
Remove all exited containers
docker images -q --filter dangling=true | xargs docker rmi
Remove all dangling images

Buildx (Multi-Platform)

docker buildx ls
List all builders and their platforms
docker buildx create --name mybuilder --use
Create a new builder and set it as active
docker buildx use mybuilder
Switch to a specific builder
docker buildx inspect --bootstrap
Start 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 mybuilder
Remove a builder
docker buildx prune
Remove build cache
docker buildx bake
Build from a bake file (docker-bake.hcl or docker-bake.json)
docker buildx bake --print
Show 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 events
Stream 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

Share this site

QR Code for cardasac.com

cardasac.com

Scan with your phone camera