Skip to content

Bash Scripting Cheatsheet — Complete Quick Reference (2026)

DodaTech Updated 2026-06-20 3 min read

In this tutorial, you'll learn about Bash Scripting Cheatsheet. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Bash is the default shell on most Linux/macOS systems, providing scripting capabilities for automation, file processing, system administration, and pipeline Orchestration.

Variables

NAME="Alice"                  # no spaces around =
readonly NAME="Bob"           # constant
echo "$NAME"                  # interpolation (use quotes!)
echo "Length: ${#NAME}"       # string length
default=${1:-"fallback"}      # default value
export PATH="$PATH:/custom"   # environment variable

Conditionals

if [ "$NAME" = "Alice" ]; then
    echo "hello"
elif [ "$NAME" = "Bob" ]; then
    echo "bye"
else
    echo "who?"
fi

# test flags
[ -f "file" ]    # file exists
[ -d "dir" ]     # directory exists
[ -z "$var" ]    # empty string
[ -n "$var" ]    # non-empty string
[ "$a" -eq "$b" ]  # numeric equal (-ne, -gt, -lt, -ge, -le)
[ "$a" = "$b" ]    # string equal (!= for not equal)

# modern [[ ]] (safer, supports && ||)
[[ "$NAME" == A* ]] && echo "starts with A"
[[ -f "file" && -r "file" ]] && echo "exists and readable"

Loops

# for
for i in {1..5}; do echo "$i"; done
for file in *.txt; do echo "$file"; done
for ((i=0; i<5; i++)); do echo "$i"; done

# while
while IFS= read -r line; do echo "$line"; done < file.txt
while [ "$count" -lt 5 ]; do ((count++)); done

# until
until ping -c1 example.com &>/dev/null; do sleep 1; done

Functions

function greet() {
    local name="$1"            # $1, $2, ... positional args
    local greeting="${2:-Hi}"  # default value
    echo "$greeting, $name!"
    return 0                   # exit status
}
greet "Alice"                  # call
greet "Bob" "Hey"

# return values (stdout-based)
get_name() { echo "Alice"; }
name=$(get_name)

Arrays

arr=("a" "b" "c")
echo "${arr[0]}"              # element
echo "${arr[@]}"              # all elements
echo "${#arr[@]}"             # length
echo "${!arr[@]}"             # indices
arr+=("d")                    # append
unset arr[1]                  # remove element

# associative arrays (Bash 4+)
declare -A map
map[name]="Alice"
echo "${map[name]}"

String Manipulation

s="hello world"
echo "${s:0:5}"               # "hello" — substring
echo "${s/world/there}"       # replace first
echo "${s//l/x}"              # replace all
echo "${s^^}"                 # uppercase
echo "${s,,}"                 # lowercase
echo "${s#hel}"               # remove prefix
echo "${s%orld}"              # remove suffix

File Operations

# read file line by line
while IFS= read -r line; do echo "$line"; done < "input.txt"

# write
echo "text" > file.txt        # overwrite
echo "text" >> file.txt       # append

# check
[ -s "file" ]                 # non-empty file
[ -r "file" ]                 # readable
[ -w "file" ]                 # writable
[ -x "file" ]                 # executable

Common One-Liners

# find and replace in files
find . -type f -name "*.txt" -exec sed -i 's/old/new/g' {} +

# backup with timestamp
cp file.txt{,.bak.$(date +%Y%m%d)}

# kill processes matching name
pkill -f "node app"

# disk usage by directory
du -sh */ | sort -rh

# watch a command every 2 seconds
watch -n2 'ps aux | grep python'

# line count (excluding blank)
grep -c . file.txt

Must-Know Items

  • Always quote variables ("$var") to prevent word splitting and globbing
  • Use [[ ]] instead of [ ] for safer, more feature-rich conditionals
  • set -e exits on error; set -u errors on undefined variables; set -o pipefail catches pipe errors
  • $? contains the last command's exit code (0 = success)
  • $@ is all args as separate words; $* is all args as single string
  • trap 'cleanup' EXIT ensures cleanup runs on script exit
  • Use $(...) not backticks (nestable, readable)
  • #!/usr/bin/env bash for portable shebang
What is the difference between `[ ]` and `[[ ]]` in Bash?

[ is the POSIX test command — requires quoting variables and uses -a/-o for AND/OR. [[ ]] is a Bash keyword that supports &&, ||, == pattern matching, =~ regex, and safer variable handling without quoting. Prefer [[ ]] for Bash scripts.

How do I handle errors in a Bash script?

Use set -euo pipefail at the top to exit on errors and undefined variables. Check exit codes with $?, use || for fallback (command || true), and trap 'cleanup' EXIT for resource cleanup. Use ${var:?error message} to fail on unset variables.

See full Linux tutorials for system administration scripting.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro