This website requires JavaScript.
🖥️ Variables
name="John"
echo $name      # Output: John
echo "${name,,}"    # Lowercase: john
echo "${name^^}"    # Uppercase: JOHN
declare -i num=42   # Integer variable
readonly name   # Make variable read-only
unset name      # Delete variable
📝 Strings
str="Hello World"
echo ${#str}        # Length
echo ${str:0:5}     # Substring
echo ${str/World/Bash} # Replace
echo "${str//l/L}" # Replace all 'l' with 'L'
echo "${str::-1}" # Remove last char
🍏 Arrays
arr=(apple banana cherry)
echo ${arr[1]}          # Access
arr[2]="grape"          # Modify
echo ${arr[@]}          # All elements
echo ${#arr[@]}         # Length
arr+=("date")                   # Add element
echo "${arr[@]:1:2}"            # Slice: banana cherry
⚖️ Conditionals
if [ $a -gt $b ]; then
  echo "a > b"
elif [ $a -eq $b ]; then
  echo "a = b"
else
  echo "a < b"
fi
# or
[[ $a -gt $b ]] && echo "a > b"
[[ -z $var ]] && echo "Empty"
[[ $str == *World* ]] && echo "Contains 'World'"
🔁 Loops
For Loop
While Loop
  for i in 1 2 3; do
    echo $i
  done
  # or
  for i in {1..5}; do echo "$i"; done
  # or
  for ((i=0; i<5; i++)); do echo "$i"; done
  count=1
  while [ $count -le 5 ]; do
    echo $count
    ((count++))
  done
  # or
  while read -r line; do echo "$line"; done < file.txt
🏷️ Functions
greet() {
  echo "Hello, $1"
}
greet "Alice"
🔄 Command Substitution
now=$(date)
echo "Current time: $now"
📁 File Test Operators
[ -f file.txt ]   # True if file exists and is regular file
[ -d /dir ]       # True if directory exists
[ -x script.sh ]  # True if file is executable
[ -r file.txt ]   # True if file is readable
[ -w file.txt ]   # True if file is writable
[ -s file.txt ]   # True if file is not empty
➕ Arithmetic
a=5
b=3
let sum=a+b
echo $sum
# or
((sum=a+b))
echo "$sum"
((a++))
((b*=2))
➗ Or
echo $((a + b))
🗣️ Input / Output
read name
echo "Hello, $name"
# or
read -p "Enter name: " name
echo -e "Hello\t$name"
📤 Redirection
command > file.txt     # Stdout to file
command >> file.txt    # Append stdout
command 2> error.txt   # Stderr to file
command &> all.txt     # Stdout + Stderr to file
# or
command > file.txt 2>&1      # Stdout & stderr to file
tee output.txt               # View and save output
🔗 Pipes
ls -l | grep ".txt"
ps aux | grep "bash" | awk '{print $2}'
sort file.txt | uniq -c | sort -nr
🧑‍💻 Process Management
ps aux          # List processes
kill -9 PID     # Kill process
top             # Real-time process monitor
pgrep bash                   # Find bash PIDs
pkill -f script.sh           # Kill by name
pstree                       # Show process tree
🏃 Job Control
command &       # Run in background
disown -h %1                 # Remove job from shell job table
jobs -l                      # List jobs with PID
jobs            # List jobs
fg %1           # Bring job to foreground
bg %1           # Continue job in background
🔒 File Permissions
chmod +x script.sh      # Make executable
chmod 755 script.sh     # rwxr-xr-x
chown user:group file   # Change owner
chmod u+x script.sh          # User execute
chmod g+w file.txt           # Group write
chmod o-r file.txt           # Others no read
🌐 Curl & Wget
curl https://example.com
wget https://example.com
🌍 Networking
ifconfig         # Show network interfaces (deprecated)
ip addr          # Recommended replacement
ip -br addr                  # Brief interface info
ping google.com
ping -c 5 google.com         # Ping 5 times
netstat -tuln    # List open ports
ss -tulnp                    # Show listening ports
📦 Archives
tar -czvf file.tar.gz folder/   # Compress
tar -xzvf file.tar.gz           # Extract
tar --exclude='*.log' -czvf backup.tar.gz folder/
zip -r file.zip folder/         # Zip folder
unzip file.zip                  # Unzip
unzip -l file.zip            # List contents
🛠️ Package Managers (Debian/Ubuntu)
sudo apt update
sudo apt install package
sudo apt remove package
apt search nginx
apt show nginx
apt list --upgradable
🔍 Searching
grep "text" file.txt
grep -rnw . -e "pattern"     # Recursive, show line numbers
find . -name "*.sh"
find /var -type f -size +10M # Files >10MB
locate filename
🕰️ History & Shortcuts
history             # Show command history
history | tail -20           # Last 20 commands
!grep                        # Run last grep command
!!                  # Repeat last command
!n                  # Repeat nth command
Ctrl + R            # Reverse search
Ctrl + C            # Cancel
Ctrl + D            # Exit
📝 Script Header
#!/usr/bin/env bash
set -euo pipefail            # Safer scripts

#!/bin/bash # above should be first line of script
📦 File Compression
gzip file.txt            # Compress file.txt to file.txt.gz
gunzip file.txt.gz       # Decompress .gz file
bzip2 file.txt           # Compress to .bz2
bunzip2 file.txt.bz2     # Decompress .bz2 file
xz file.txt              # Compress to .xz
unxz file.txt.xz         # Decompress .xz file
tar -caf archive.tar.xz folder/
xz -d archive.tar.xz
💾 Disk Usage
df -h                   # Show disk usage in human-readable form
df -Th                       # Filesystem type & usage
du -h --max-depth=1          # Folder sizes, one level
du -sh *                # Show sizes of all files/folders in current dir
du -ah | sort -rh       # Sort files by size
📅 Date & Time
date                    # Current date and time
date -u                      # UTC time
date "+%Y-%m-%d"        # Format date output
date -d "2 days ago"
date -d "next monday"   # Get date of next Monday
🌱 Environment Variables
echo $HOME              # Show home directory
export VAR=value        # Set env variable
env                     # List environment variables
unset VAR               # Unset variable

export PATH="$PATH:/opt/bin"
printenv | sort
✨ Shell Expansion
echo *                  # All files in current dir
echo {1..5}             # 1 2 3 4 5
echo {a,b,c}.txt        # a.txt b.txt c.txt
echo {A..Z}{0..9}            # A0 A1 ... Z9
🗄️ Backups
cp file{,.bak}          # Quick copy to file.bak
rsync -av folder/ backup/   # Sync folders with backup
rsync -a --delete src/ dest/ # Mirror backup
⏰ Crontab (Scheduled Tasks)
crontab -e              # Edit user crontab
crontab -l              # List scheduled jobs
crontab -l | grep backup
crontab -r              # Remove crontab
📝 Crontab Syntax
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of week (0 - 6) (Sunday=0)
# │ │ │ │ │
# * * * * * <command to execute>

0 9 * * * /path/to/script.sh     # Run at 9 AM daily
CSS