Bash Scripting Cheat Sheet
Practical Bash scripting reference covering variables, conditionals, loops, string/array handling, and common builtins.
2 PagesBeginnerApr 10, 2026
Basics
Variables and script arguments.
bash
#!/bin/bash# Variables (no spaces around =)name="World"echo "Hello, $name!"readonly PI=3.14159 # constantecho "Args: $1 $2, count: $#"echo "Script name: $0"
Conditionals
if/elif/else and test expressions.
bash
x=10if [ "$x" -gt 5 ]; then echo "big"elif [ "$x" -eq 5 ]; then echo "equal"else echo "small"fi# String comparison[ "$name" == "World" ] && echo "matched"# Test file existence[ -f "/etc/passwd" ] && echo "file exists"
Loops
for and while loops.
bash
for i in 1 2 3 4 5; do echo "i=$i"donefor f in *.txt; do echo "Found $f"donecount=0while [ $count -lt 3 ]; do echo "count=$count" count=$((count + 1))done
Strings & Arrays
Manipulating strings and arrays.
- ${#str}- Length of a string
- ${str:0:3}- Substring starting at index 0, length 3
- arr=(a b c)- Declares an indexed array
- ${arr[@]}- Expands to all array elements
- ${arr[1]}- Accesses the element at index 1
- ${str/foo/bar}- Replaces the first occurrence of foo with bar
Common Builtins
Useful builtins and idioms.
- $(cmd)- Command substitution, captures command output
- set -euo pipefail- Exit on error, unset variable, or pipeline failure
- trap 'cleanup' EXIT- Runs the cleanup function when the script exits
- read -p "Prompt: " var- Prompts for and reads user input into var
- function name() { ...; }- Defines a reusable shell function
- $?- Exit status of the last executed command
Functions & Arguments
Defining functions and handling positional parameters.
bash
greet() { local name="$1" local greeting="${2:-Hello}" # default value echo "$greeting, $name" return 0}greet "World"greet "Ada" "Hi"# all args, count, and script nameecho "count: $# all: $* script: $0"
Parameter Expansion
Inline string manipulation on variables.
- ${var:-default}- use default if var is unset or empty
- ${var:=default}- assign default to var if unset, then expand
- ${var:?msg}- error out with msg if var is unset or empty
- ${#var}- length of the value in characters
- ${var#pattern}- remove shortest matching prefix
- ${var%pattern}- remove shortest matching suffix
- ${var/old/new}- replace first occurrence of old with new
- ${var:offset:len}- substring starting at offset for len chars
Error Handling & Traps
Fail fast and clean up on exit.
bash
#!/usr/bin/env bashset -euo pipefail # exit on error, unset var, pipe failuretmp=$(mktemp)cleanup() { rm -f "$tmp"; }trap cleanup EXITtrap 'echo "Error on line $LINENO" >&2' ERRif ! command -v git >/dev/null 2>&1; then echo "git is required" >&2 exit 1fi
Command Substitution & Process Substitution
Capture output and feed streams as files.
bash
now=$(date +%Y-%m-%d)files=$(ls *.txt 2>/dev/null)# arithmeticcount=$(( 3 + 4 ))(( count++ ))# process substitution: diff two commands' outputdiff <(sort a.txt) <(sort b.txt)# read command output line by linewhile IFS= read -r line; do echo "got: $line"done < <(grep foo data.txt)
Parsing Options with getopts
Handle -flag and -o value command-line options.
bash
verbose=0output=""while getopts ":vo:h" opt; do case $opt in v) verbose=1 ;; o) output="$OPTARG" ;; h) echo "usage: $0 [-v] [-o file]"; exit 0 ;; \?) echo "bad option: -$OPTARG" >&2; exit 1 ;; :) echo "-$OPTARG needs a value" >&2; exit 1 ;; esacdoneshift $((OPTIND - 1)) # remaining args are positional
Pro Tip
Always quote variable expansions ("$var") to prevent word splitting and glob expansion on values containing spaces or special characters.
Was this cheat sheet helpful?
Explore Topics
#BashScripting#BashScriptingCheatSheet#Programming#Beginner#Conditionals#Loops#StringsArrays#CommonBuiltins#DataStructures#CommandLine#CheatSheet#SkillVeris