Shell Cheat Sheet
· 7 min read
File & Directory Navigation
Quick navigation:
cd - # Switch to previous directory
pushd /path && popd # Save current dir, go to path, then return
!! # Repeat last command
Working with Bash History
Basic history commands:
history # Show all command history
history 20 # Show last 20 commands
history | grep docker # Search history for specific command
!123 # Execute command #123 from history
!docker # Execute most recent command starting with "docker"
!?search # Execute most recent command containing "search"
History argument shortcuts:
!$ # Last argument of previous command
!^ # First argument of previous command
!* # All arguments of previous command
!:2 # Second argument of previous command
!:2-4 # Arguments 2 through 4
!:2* # Arguments 2 through end
!:2-$ # Arguments 2 through last
# Example usage:
# After: ls /var/log/nginx/access.log
vim !$ # Opens vim /var/log/nginx/access.log
Interactive history search:
ctrl+r # Search history backward (type to search)
ctrl+g # Exit search without running
ctrl+o # Execute found command (after ctrl+r)
History navigation (in command line):
ctrl+p or ↑ # Previous command
ctrl+n or ↓ # Next command
Managing history:
history -c # Clear current session history
history -w # Write current history to file
history -d 123 # Delete command #123 from history
history -a # Append current session to history file
cat /dev/null > ~/.bash_history # Clear entire history file
History configuration (add to ~/.bashrc):
export HISTSIZE=10000 # Commands to keep in memory
export HISTFILESIZE=20000 # Commands to keep in history file
export HISTTIMEFORMAT="%F %T " # Add timestamps to history
export HISTCONTROL=ignoredups # Ignore duplicate commands
export HISTCONTROL=ignoreboth # Ignore duplicates and commands starting with space
export HISTIGNORE="ls:pwd:exit:clear" # Don't save these commands
shopt -s histappend # Append to history, don't overwrite
Advanced history tricks:
fc # Open last command in $EDITOR to modify
fc 100 105 # Edit commands 100-105 in editor
fc -l -10 # List last 10 commands
fc -s docker # Re-execute last docker command
# Run command without saving to history (note the leading space):
secret-command # (requires HISTCONTROL=ignorespace)
# Execute multiple history commands:
!123 && !125 # Run commands 123 and 125
History with grep patterns:
history | grep "git commit" # Find all git commits
history | grep -E "npm|yarn" # Find npm or yarn commands
history | awk '{$1=""; print $0}' # Print history without numbers
history | tail -20 | head -10 # Show commands 11-20 from the end
Quick command editing:
# After typing a long command with a typo:
^typo^correct # Replace first occurrence
!!:gs/old/new # Replace all occurrences in last command
!:0 new-arg !:2-$ # Reuse command with different first arg
Useful history aliases (add to ~/.bashrc):
alias h='history'
alias h1='history 10'
alias h2='history 20'
alias h3='history 30'
alias hgrep='history | grep'
alias histop='history | awk "{print \$2}" | sort | uniq -c | sort -rn | head -10'
FZF integration for enhanced history search:
# If fzf is installed, add to ~/.bashrc:
[ -f ~/.fzf.bash ] && source ~/.fzf.bash
# Then use:
ctrl+r # Interactive fuzzy history search (much better!)
# Custom history search command:
h() {
eval $(history | fzf --tac | sed 's/^[ ]*[0-9]*[ ]*//')
}
Zsh-specific history features:
# (if using zsh instead of bash)
!!:s/old/new # Substitute in last command
r old=new # Quick substitution
fc -l -20 # List last 20 commands
history -i # Show timestamps
autoload -U history-search-end # Better history search
Finding Files & Content
Find files by name:
find . -name "*.js" # Find all .js files
find . -iname "config*" # Case-insensitive search
fd "pattern" # Modern alternative (faster)
fd -e py # Find all .py files
Find files by content:
grep -r "function_name" . # Recursive search in current dir
grep -rn "TODO" --include="*.js" . # Search with line numbers, specific files
rg "pattern" # ripgrep (much faster)
rg -t python "def.*function" # Search specific file types
ag "search_term" # The Silver Searcher (also fast)
Fuzzy finding:
fzf # Interactive fuzzy finder
vim $(fzf) # Open selected file in vim
cat $(fzf) # View selected file
ctrl+r # Fuzzy search command history (if fzf installed)
Process Management
Finding & killing processes:
ps aux | grep nginx # Find process by name
pgrep nginx # Get PID by process name
pkill nginx # Kill process by name
kill -9 PID # Force kill by PID
killall process_name # Kill all instances
lsof -i :8080 # See what's using port 8080
netstat -tulpn | grep :8080 # Alternative port check
Process monitoring:
top # Real-time process viewer
htop # Better interactive process viewer
watch -n 1 "ps aux | grep node" # Monitor command every 1 second
File Operations
Bulk operations:
find . -name "*.log" -delete # Delete all .log files
find . -name "*.txt" -exec chmod 644 {} \; # Change permissions
rename 's/\.txt$/.md/' *.txt # Batch rename (Perl rename)
File inspection:
head -n 20 file.txt # First 20 lines
tail -n 50 file.txt # Last 50 lines
tail -f app.log # Follow log file in real-time
less +F file.log # Like tail -f but scrollable
wc -l file.txt # Count lines
Disk Usage & System Info
df -h # Disk space human-readable
du -sh * # Size of each item in current dir
du -sh * | sort -h # Sorted by size
ncdu # Interactive disk usage analyzer
free -h # Memory usage
uptime # System uptime and load
Text Processing
Useful one-liners:
cat file.txt | sort | uniq # Remove duplicates
awk '{print $1}' file.txt # Print first column
sed 's/old/new/g' file.txt # Replace text
cut -d',' -f1,3 data.csv # Extract CSV columns
jq '.name' data.json # Parse JSON
Git Shortcuts
git log --oneline --graph --all # Visual commit history
git diff --staged # See staged changes
git stash # Temporarily store changes
git stash pop # Restore stashed changes
git branch -d branch_name # Delete local branch
git clean -fd # Remove untracked files/dirs
git reflog # See all ref changes (recover lost commits)
Network & HTTP
curl -I https://example.com # Get headers only
curl -o output.txt https://url # Download to file
wget -r -np -k https://site.com # Mirror website
ping -c 4 google.com # Ping 4 times then stop
traceroute google.com # Trace route to host
ss -tulpn # Socket statistics (modern netstat)
Docker Quick Commands
docker ps # Running containers
docker ps -a # All containers
docker images # List images
docker logs -f container_name # Follow container logs
docker exec -it container_name bash # Shell into container
docker system prune -a # Clean up everything
docker-compose up -d # Start services in background
Permissions & Ownership
chmod +x script.sh # Make executable
chmod 644 file.txt # rw-r--r--
chmod 755 script.sh # rwxr-xr-x
chown user:group file.txt # Change owner
sudo chown -R $USER:$USER dir/ # Recursively claim ownership
Archive & Compression
tar -czf archive.tar.gz folder/ # Create compressed archive
tar -xzf archive.tar.gz # Extract compressed archive
tar -tzf archive.tar.gz # List contents without extracting
unzip file.zip # Extract zip
zip -r archive.zip folder/ # Create zip archive
SSH & Remote
ssh user@host # Connect to remote
ssh -i key.pem user@host # Connect with key file
scp file.txt user@host:/path/ # Copy file to remote
scp user@host:/path/file.txt . # Copy from remote
rsync -avz source/ user@host:/dest/ # Sync directories
Useful Aliases to Add to ~/.bashrc or ~/.zshrc
alias ll='ls -alh'
alias ..='cd ..'
alias ...='cd ../..'
alias gs='git status'
alias gp='git pull'
alias gc='git commit -m'
alias ports='netstat -tulanp'
alias meminfo='free -h'
alias psg='ps aux | grep -v grep | grep -i -e VSZ -e'
Advanced Search Patterns
Find and replace across files:
find . -name "*.js" -exec sed -i 's/oldText/newText/g' {} \;
Find recently modified files:
find . -mtime -7 # Modified in last 7 days
find . -mmin -60 # Modified in last 60 minutes
Find large files:
find . -type f -size +100M # Files larger than 100MB