โ Back to Cheat Sheets
๐ป Command Line Cheat Sheet
Complete terminal reference โ navigation, text processing, permissions, ssh, compression, cron, Docker, and system admin.
Navigation & Files
Directory Navigation
pwd # Print working directory
ls -la # List all (hidden + details)
ls -lh # Human-readable sizes
ls -lt # Sort by modified time
cd ~/projects # Home-relative path
cd - # Previous directory
mkdir -p a/b/c # Create nested dirs
tree -L 2 # Directory tree (2 levels)
tree -I 'node_modules|.git' # Exclude patternsNavigate and inspect directories.
File Operations
cp file.txt backup/ # Copy file
cp -r src/ dest/ # Copy directory recursively
mv old.txt new.txt # Move / rename
rm file.txt # Remove file
rm -rf temp_dir/ # Remove dir recursively (CAREFUL!)
touch new_file.txt # Create empty / update timestamp
ln -s /path/to/target link # Symbolic link
ln target hardlink # Hard link
stat file.txt # Detailed file infoCopy, move, delete, and link files.
File Viewing
cat file.txt # Print entire file
head -n 20 file.txt # First 20 lines
tail -n 20 file.txt # Last 20 lines
tail -f server.log # Follow log output (live)
less large_file.txt # Scrollable viewer (q to quit)
wc -l file.txt # Line count
wc -w file.txt # Word count
wc -c file.txt # Byte count
file mystery.dat # Detect file type
diff file1.txt file2.txt # Compare filesView, inspect, count, and compare file contents.
Find Command
find . -name '*.py' # Find by name
find . -name '*.log' -mtime +30 # Modified 30+ days ago
find . -type f -size +100M # Files > 100MB
find . -name '*.tmp' -delete # Find and delete
find . -name '*.py' -exec wc -l {} + # Execute on results
find . -empty # Empty files/dirs
find . -perm 777 # Find by permissions
# locate (faster, uses index)
locate '*.conf'
updatedb # Refresh locate indexPowerful file search with filters and actions.
Text Processing
grep โ Pattern Search
grep 'ERROR' app.log # Search for pattern
grep -r 'TODO' src/ # Recursive search
grep -i 'warning' log.txt # Case insensitive
grep -n 'def ' main.py # Show line numbers
grep -c 'pattern' file.txt # Count matches
grep -v 'DEBUG' app.log # Invert (exclude)
grep -l 'import' *.py # List files only
grep -A 3 -B 1 'ERROR' log.txt # Context (3 after, 1 before)
grep -E '(error|warn)' log.txt # Extended regex (egrep)
grep -P '\d{3}-\d{4}' contacts # Perl regexSearch text patterns with context and regex.
sed โ Stream Editor
sed 's/old/new/g' file.txt # Find & replace (stdout)
sed -i 's/http/https/g' config.yml # In-place edit
sed -n '5,10p' file.txt # Print lines 5-10
sed '3d' file.txt # Delete line 3
sed '/^$/d' file.txt # Delete empty lines
sed 's/^ *//' file.txt # Trim leading spaces
sed -n '/START/,/END/p' file.txt # Print between patternsStream editing โ replace, delete, extract lines.
awk โ Column Processing
awk '{print $1, $3}' data.txt # Print columns 1 & 3
awk -F',' '{print $2}' data.csv # CSV: print column 2
awk '{sum += $3} END {print sum}' f # Sum column 3
awk 'NR > 1 {print $0}' file.txt # Skip header row
awk '$3 > 100 {print $1, $3}' f # Filter by value
awk '{print NR": "$0}' file.txt # Add line numbers
awk '!seen[$1]++' file.txt # Unique by column 1Column-based text processing and aggregation.
sort, uniq, cut, tr
sort file.txt # Sort lines alphabetically
sort -n file.txt # Numeric sort
sort -k 2 -t',' data.csv # Sort by column 2 (comma delim)
sort -u file.txt # Sort + unique
uniq file.txt # Remove consecutive dupes
sort file.txt | uniq -c # Count occurrences
cut -d',' -f1,3 data.csv # Extract columns 1 & 3
cut -c1-10 file.txt # First 10 characters per line
tr 'a-z' 'A-Z' < file.txt # Uppercase
tr -d '\r' < file.txt # Remove carriage returns
tr -s ' ' < file.txt # Squeeze spacesSort, deduplicate, extract columns, and transform.
Pipes & Redirection
cat log.txt | grep ERROR | wc -l # Count errors
ps aux | sort -k 3 -rn | head -5 # Top 5 by CPU
history | grep 'docker' # Search history
# Redirection
command > out.txt # Stdout to file (overwrite)
command >> out.txt # Stdout append
command 2> err.txt # Stderr to file
command > out.txt 2>&1 # Both stdout+stderr
command &> all.txt # Same (bash shorthand)
command < input.txt # Stdin from file
# tee: stdout + file simultaneously
command | tee output.txt
command | tee -a output.txt # Append modeChain commands and redirect I/O streams.
Permissions & Ownership
chmod & chown
chmod 755 script.sh # rwxr-xr-x
chmod +x script.sh # Add execute
chmod -R 644 dir/ # Recursive
# Permission digits: r=4, w=2, x=1
# 755 = rwxr-xr-x (owner: all, group/others: read+exec)
# 644 = rw-r--r-- (owner: rw, group/others: read)
# 700 = rwx------ (owner only)
chown user:group file.txt
chown -R deploy:www /var/www/Set file permissions and ownership.
Users & Groups
whoami # Current user
id # User ID, groups
groups username # User's groups
sudo useradd newuser # Create user
sudo passwd newuser # Set password
sudo usermod -aG docker user # Add to group
su - username # Switch user
sudo command # Run as rootManage users, groups, and sudo access.
System & Process
Process Management
ps aux # List all processes
ps aux | grep python # Filter processes
top # Real-time monitor
htop # Better interactive monitor
kill <PID> # Graceful kill (SIGTERM)
kill -9 <PID> # Force kill (SIGKILL)
killall python # Kill all by name
pkill -f 'pattern' # Kill by pattern
nohup script.sh & # Background, survive logout
jobs # List background jobs
fg %1 # Bring job 1 to foreground
bg %1 # Resume in background
Ctrl+Z # Suspend foreground processMonitor and control processes.
Disk Usage
df -h # Disk space by filesystem
df -h / # Root partition
du -sh folder/ # Folder total size
du -sh * | sort -rh | head -10 # Top 10 largest
ncdu # Interactive disk usage
lsblk # List block devices
mount | column -t # Mounted filesystemsCheck disk space and storage.
Networking
curl -s https://api.example.com | jq '.'
curl -X POST -H 'Content-Type: application/json' \
-d '{"key":"val"}' https://api.example.com
wget https://example.com/file.zip
wget -O output.zip https://example.com/file.zip
ping -c 4 google.com # Connectivity check
nslookup domain.com # DNS lookup
netstat -tlnp # Open ports
ss -tulnp # Modern netstat
lsof -i :8080 # What's on port 8080HTTP requests, downloads, DNS, and port inspection.
SSH & Compression
SSH & SCP
ssh user@host.com # Connect
ssh -i key.pem user@host # Connect with key
ssh -p 2222 user@host # Custom port
# Copy files over SSH
scp file.txt user@host:/path/
scp -r folder/ user@host:/path/
scp user@host:/remote/file.txt ./local/
# SSH tunnel (port forwarding)
ssh -L 8080:localhost:80 user@host # Local forward
ssh -N -L 5432:db-host:5432 bastion-host # DB tunnel
# SSH config (~/.ssh/config)
# Host myserver
# HostName 1.2.3.4
# User deploy
# IdentityFile ~/.ssh/my_keyRemote access, file transfer, and tunneling.
Compression
# tar (archive + compress)
tar -czf archive.tar.gz folder/ # Create gzip
tar -xzf archive.tar.gz # Extract gzip
tar -cjf archive.tar.bz2 folder/ # Create bzip2
tar -xjf archive.tar.bz2 # Extract bzip2
tar -tf archive.tar.gz # List contents
# zip
zip -r archive.zip folder/
unzip archive.zip
unzip -l archive.zip # List contents
# gzip single file
gzip file.txt # Compresses to file.txt.gz
gunzip file.txt.gz # DecompressArchive and compress/decompress files.
Environment & Cron
Environment Variables
echo $PATH # Print variable
export MY_VAR='value' # Set for session
unset MY_VAR # Remove
# Persist in ~/.bashrc or ~/.zshrc
echo 'export API_KEY=abc' >> ~/.bashrc
source ~/.bashrc # Reload
env # All env vars
printenv HOME # Specific var
which python # Find executable
type -a python # All locationsSet and manage environment variables.
Cron Jobs
crontab -e # Edit cron jobs
crontab -l # List cron jobs
# Format: min hour day month weekday command
0 * * * * /scripts/hourly.sh # Every hour
30 2 * * * /scripts/nightly.sh # Daily 2:30 AM
0 0 * * 0 /scripts/weekly.sh # Weekly Sunday
*/5 * * * * /scripts/check.sh # Every 5 minutes
0 9 1 * * /scripts/monthly.sh # 1st of month 9 AM
# Redirect output
0 * * * * /scripts/job.sh >> /var/log/job.log 2>&1Schedule recurring tasks with cron.
Docker Basics
Container Management
docker run -d --name myapp -p 8080:80 nginx
docker run -it ubuntu bash # Interactive shell
docker ps # Running containers
docker ps -a # All containers
docker stop myapp
docker start myapp
docker rm myapp
docker logs -f myapp # Follow logs
docker exec -it myapp bash # Shell into runningRun, stop, and manage Docker containers.
Images & Volumes
docker images # List images
docker pull python:3.11
docker build -t myapp:v1 .
docker rmi image_name # Remove image
# Volumes (persistent data)
docker volume create mydata
docker run -v mydata:/app/data myapp
docker run -v $(pwd):/app myapp # Bind mount
# Docker Compose
docker compose up -d
docker compose down
docker compose logs -fBuild images and manage persistent storage.
xargs & Miscellaneous
xargs
# Run command for each input line
find . -name '*.log' | xargs rm
find . -name '*.py' | xargs grep 'TODO'
cat urls.txt | xargs -I {} curl -s {}
echo '1 2 3' | xargs -n 1 echo # One arg per run
find . -name '*.jpg' | xargs -P 4 -I {} convert {} {}.png # ParallelBuild commands from standard input.
Aliases & History
alias ll='ls -la'
alias gs='git status'
alias dc='docker compose'
alias k='kubectl'
# Persist in ~/.bashrc or ~/.zshrc
echo "alias ll='ls -la'" >> ~/.bashrc
history # Command history
!! # Repeat last command
!grep # Last command starting with grep
Ctrl+R # Reverse search historyCreate shortcuts and search command history.