Bash Cheat Sheet

Shell Syntax & Structure

Commands are written line by line. Use semicolon ; to separate multiple commands on one line.

echo "First"; echo "Second"

Comments (#)

Anything after # is considered a comment and ignored by the shell.

# This is a comment
echo "Hello" # This is also a comment

Variables (set, read, export)

# Setting a variable
name="Alice"
echo "Name is: $name"

# Reading input into a variable
echo "Enter your favorite color:"
read favorite_color
echo "Your favorite color is: $favorite_color"

# Exporting a variable to make it available to child processes
export PATH="$PATH:/usr/local/myapp/bin"
echo "Updated PATH: $PATH"

Quoting (single, double, backticks)

echo 'Single quotes: $HOME'
echo "Double quotes: $HOME"
echo `date`

Command Substitution (`cmd`, $(cmd))

# Preferred modern syntax: $(command)
today=$(date '+%A, %B %d, %Y')
echo "Today is: $today"

current_user=$(whoami)
echo "Current user: $current_user"

Escape Characters

echo "This is a quote: \""
echo -e "Line1
Line2"

ls, cd, pwd

ls         # List directory contents
cd /path   # Change to directory
pwd        # Print working directory

cp, mv, rm

cp source.txt destination.txt   # Copy a file
mv oldname.txt newname.txt      # Rename/move file
rm file.txt                     # Delete a file
rm -r folder/                   # Delete directory recursively

mkdir, rmdir, touch, stat, find, locate

mkdir new_folder       # Create directory
rmdir empty_folder     # Remove empty directory
touch newfile.txt      # Create empty file or update timestamp
stat file.txt          # File details
find . -name "*.sh"    # Find files recursively
locate filename        # Search file paths (needs updatedb)

cat, less, more

cat file.txt       # View entire file
less file.txt      # Scrollable viewer (q to quit)
more file.txt      # View page by page

head, tail

head file.txt       # First 10 lines
tail file.txt       # Last 10 lines
tail -f log.txt     # Live updates as file changes

cut, awk, sed

cut -d":" -f1 /etc/passwd         # Cut first field using colon delimiter
awk '{ print $1 }' file.txt       # Print first column
sed 's/foo/bar/g' file.txt        # Replace 'foo' with 'bar'

grep, sort, uniq

grep "search" file.txt            # Search lines containing 'search'
sort file.txt                     # Sort lines alphabetically
uniq sorted.txt                   # Remove duplicate lines

wc, tee, tr

wc -l file.txt                    # Line count
tee output.txt                   # Redirect output to file and screen
tr 'a-z' 'A-Z'                   # Convert lowercase to uppercase

chmod, chown, chgrp

chmod +x script.sh               # Make script executable
chmod 644 file.txt               # rw-r--r-- permissions
chown user file.txt              # Change file owner
chgrp group file.txt             # Change file group

umask

umask                           # Show default permission mask
umask 022                       # Set default mask to allow rw-r--r--

File permission symbols (rwx)

Each file has permissions for owner, group, and others.

r - read
w - write
x - execute

Example: -rwxr-xr--
Owner: rwx (7), Group: r-x (5), Others: r-- (4)

ps, top, htop

ps aux                         # List all processes
top                            # Real-time system monitor
htop                           # Enhanced top (install separately)

kill, killall, pkill

kill 1234                      # Kill process by PID
killall firefox                # Kill all processes by name
pkill -f "pattern"             # Kill using pattern match

&, nohup, disown

./script.sh &                  # Run in background
nohup ./script.sh &            # Run in background, immune to hangups
disown                         # Remove job from shell's job table

jobs, fg, bg

jobs                           # List current jobs
fg %1                          # Bring job 1 to foreground
bg %1                          # Resume job 1 in background

>, >>, <

command > file.txt             # Redirect stdout (overwrite)
command >> file.txt            # Redirect stdout (append)
command < input.txt            # Take input from file

2>, 2>&1

command 2> error.log           # Redirect stderr
command > all.log 2>&1        # Redirect stdout and stderr to same file

| (pipe)

cat file.txt | grep "search"   # Output of one command becomes input of another

xargs

cat list.txt | xargs rm        # Run rm for each line in list.txt
find . -name "*.log" | xargs rm

if / else / elif

x=5

# if
if [ "$x" -lt 10 ]; then
  echo "x is less than 10"
fi

# if-else
if [ "$x" -eq 10 ]; then
  echo "x is 10"
else
  echo "x is not 10"
fi

# if-elif-else
if [ "$x" -gt 10 ]; then
  echo "x is greater than 10"
elif [ "$x" -eq 10 ]; then
  echo "x is 10"
else
  echo "x is less than 10"
fi

case

case $fruit in
  apple)
    echo "Apple pie!";;
  banana)
    echo "Banana smoothie!";;
  *)
    echo "Unknown fruit";;
esac

for, while, until loops

for i in 1 2 3; do
  echo $i
done

while [ $x -lt 5 ]; do
  echo $x
  x=$((x+1))
done

until [ $x -eq 5 ]; do
  echo $x
  x=$((x+1))
done

break, continue

for i in {1..10}; do
  if [ $i -eq 3 ]; then
    continue
  fi
  if [ $i -eq 7 ]; then
    break
  fi
  echo $i
done

select

select option in "Start" "Stop" "Exit"; do
  echo "You chose: $option"
  break
done

Defining & Calling Functions

greet() {
  echo "Hello, $1!"
}

greet "Alice"

Function Parameters

Functions in Bash can accept arguments, which are accessed using special variables like $1, $@, and $#.

my_func() {
  echo "First: $1"
  echo "Second: $2"
  echo "All: $@"
  echo "Count: $#"
}

my_func "apple" "banana" "cherry"

Return Values

Bash functions can return integer values (0–255) using the return statement. These are typically used to indicate success (0) or failure (non-zero), and can be accessed using $? immediately after the function call.

is_even() {
  return $(( $1 % 2 ))
}

is_even 4
if [ $? -eq 0 ]; then
  echo "Even"
else
  echo "Odd"
fi
is_even 4 if [ $? -eq 0 ]; then echo "Even" else echo "Odd" fi

Test Conditions ([ ], [[ ]])

Conditional expressions using [ ] and [[ ]]. [[ ]] is more flexible for string operations and supports pattern matching.

a=5
b=10
str="hello"

[ "$a" -eq "$b" ]        # False: a is not equal to b
[ "$a" -ne "$b" ]        # True: a is not equal to b
[[ "$str" == "hello" ]]  # True: string comparison
[[ "$str" == h* ]]       # True: pattern match with [[ ]]

String Comparison

[ "$a" = "$b" ]          # Equal
[ "$a" != "$b" ]         # Not equal
[ -z "$a" ]              # Empty string
[ -n "$a" ]              # Non-empty string

Regex Basics

Bash supports basic regular expressions within double square brackets using the =~ operator. This allows pattern matching against strings.

word="hello123"

# Check if the word contains only letters
[[ $word =~ ^[a-zA-Z]+$ ]] && echo "Only letters"

# Check if the word contains only digits
[[ $word =~ ^[0-9]+$ ]] && echo "Only digits"

# Check if the word starts with "hello"
[[ $word =~ ^hello ]] && echo "Starts with 'hello'"

Globbing (*, ?, [])

Globbing allows pattern-based matching of filenames and paths. It is commonly used to match multiple files using wildcards like *, ?, and character sets [].

*.txt           # Matches all files ending in .txt
file?.txt       # Matches file1.txt, fileA.txt (any single character)
file[1-3].txt   # Matches file1.txt, file2.txt, file3.txt

Declaring Arrays

arr=(one two three)
echo ${arr[0]}

Indexing & Iterating

for i in "${arr[@]}"; do
  echo $i
done
echo "Length: ${#arr[@]}"

Associative Arrays (declare -A)

declare -A colors
colors[apple]=red
colors[banana]=yellow
echo ${colors[apple]}

Shebang (#!)

The shebang line at the top of a script specifies the path to the interpreter that should execute the script. It must be the very first line in the file.

#!/bin/bash
echo "Running with Bash"

Script Arguments ($0, $1, $@, $#)

echo "Script name: $0"
echo "First arg: $1"
echo "All args: $@"
echo "Arg count: $#"

Exit Status ($?, exit)

command
if [ $? -eq 0 ]; then
  echo "Success"
else
  echo "Failure"
fi

exit 1     # Exit script with status 1

Debugging (set -x, set -e)

set -x      # Echo commands before execution
set -e      # Exit on error

apt, yum, pacman, brew

# Debian/Ubuntu
sudo apt update && sudo apt install package

# Red Hat/CentOS
sudo yum install package

# Arch Linux
sudo pacman -S package

# macOS (Homebrew)
brew install package

uname, whoami, hostname

uname -a        # Kernel and system info
whoami          # Current user
hostname        # Hostname of system

df, du, free, uptime

df -h           # Disk usage by mounted filesystems
du -sh *        # Disk usage of current directory contents
free -h         # Memory usage
uptime          # System uptime and load average

env, printenv

env             # Show all environment variables
printenv PATH   # Show specific environment variable

ping, curl, wget

ping example.com            # Check connectivity
curl http://example.com     # Get HTTP content
wget http://example.com     # Download a file

ssh, scp, rsync

ssh user@host               # Remote login
scp file user@host:/path    # Copy file to remote server
rsync -av src/ dest/        # Sync directories

netstat, ss, ifconfig/ip

netstat -tuln               # Network ports (deprecated)
ss -tuln                    # Modern alternative to netstat
ifconfig                    # Show interfaces (deprecated)
ip addr                     # Show interfaces (replacement)

crontab (scheduling)

crontab -e                  # Edit user's cron jobs
crontab -l                  # List cron jobs
# Example: run every day at 6am
0 6 * * * /path/to/script.sh

Aliases

alias ll='ls -la'
unalias ll
alias grep='grep --color=auto'

History and !!, !n, !string

history                 # Show command history
!!                      # Run last command
!42                     # Run command number 42
!git                    # Run last command starting with 'git'

trap, signals

trap "echo Goodbye!" EXIT          # Run on script exit
trap "cleanup" INT                # Run on Ctrl+C (SIGINT)
sleep 60                          # Wait to allow trap test