#!/bin/bash
Shebang (script interpreter)
set -euo pipefail
Exit on error, undefined vars, pipe fail
echo "Hello World"
Print line
read -p "Name: " name
Read user input with prompt
read -s password
Read silent input (passwords)
# This is a comment
Comment
name="Alice"
Assign variable (no spaces!)
echo "$name"
Read variable
echo "${name}!" Brace syntax for clarity
readonly PI=3.14
Read-only constant
unset name
Remove variable
export PATH="$HOME/bin:$PATH"
Export to subshells
${var:-default} Default if unset
${var:=default} Default and assign if unset
${var:?error message} Error if unset
${#var} String length
${var:0:3} Substring (offset 0, length 3)
${var/old/new} Replace first occurrence
${var//old/new} Replace all occurrences
if [ "$x" -eq 1 ]; then echo "one" fi
If with numeric compare
if [[ "$s" == "hi" ]]; then ... fi
If with string compare ([[ ]])
if [ -f file.txt ]; then ... fi
If file exists
if [ -d /etc ]; then ... fi
If directory exists
if [ -z "$x" ]; then ... fi
If string is empty
if [ -n "$x" ]; then ... fi
If string is non-empty
-eq -ne -lt -le -gt -ge
Numeric operators
[[ "$s" =~ ^[0-9]+$ ]]
Regex match
case "$x" in 1) ... ;; 2|3) ... ;; *) ... ;; esac
Case statement
[ -f file ] && echo exists || echo missing
Inline if/else
for i in 1 2 3; do echo $i; done
For over list
for i in {1..10}; do ... done For over range
for i in $(seq 1 10); do ... done
For with seq
for f in *.txt; do ... done
For over files (glob)
for ((i=0; i<10; i++)); do ... done
C-style for loop
while [ "$n" -lt 10 ]; do n=$((n+1)) done
While loop
while read line; do echo "$line"; done < file.txt
Read file line by line
until [ condition ]; do ... done
Until loop (negated while)
break continue
Break/continue loop
arr=(a b c d)
Create array
echo "${arr[0]}" Access by index
echo "${arr[@]}" All elements
echo "${#arr[@]}" Array length
arr+=(e f)
Append elements
for item in "${arr[@]}"; do ... done Iterate array
declare -A map map[key]="value"
Associative array (dict)
greet() {
echo "Hi $1"
}
greet "Alice" Define and call function
$1 $2 $3 ... $@ $#
Args: pos 1, 2, 3, all, count
local x=5
Function-local variable
return 0
Exit code from function
command > file.txt
Redirect stdout (overwrite)
command >> file.txt
Redirect stdout (append)
command 2> errors.log
Redirect stderr
command &> both.log
Redirect stdout + stderr
command < input.txt
Input from file
cmd1 | cmd2 | cmd3
Pipe between commands
$(command)
Command substitution
$((2 + 3))
Arithmetic expansion
cmd1 && cmd2 || cmd3
Run cmd2 if cmd1 succeeds, else cmd3
cmd &
Run in background
wait
Wait for background jobs
trap 'cleanup' EXIT
Run on script exit
Bash Cheat Sheet — Variables, Loops, Conditionals & Pipes Reference
Bash has shipped as the default shell on Linux servers since the early nineties, and the core grammar has barely shifted since — variables, conditionals, loops, pipes, file tests. The cheatsheet below covers more than 60 snippets across those areas plus parameter expansion and array operations. Most trouble in real scripts doesn't come from forgetting syntax. It comes from quirks that look ordinary but bite. A stray space around `=` turns an assignment into a command lookup that fails. `set -e` quietly stops protecting the script the moment two commands get chained with a pipe. An unquoted variable holding a value with a space in it splits into separate words and breaks every test downstream. The snippets below are the ones a script author reaches for while debugging exactly that — the right comparison operator, the right expansion, the right redirection — without rereading the Bash manual from line one each time.
Common pitfalls in Bash
A few patterns earn their place on the first screen of any Bash script. `set -euo pipefail` at the top keeps errors in plain sight — the shell exits on the first error, undefined variables count as errors, and pipe failures propagate. It doesn't catch everything, but it catches considerably more than the default `set -e` alone. Variable quoting matters: `"$file"` not `$file`, every single time, because the moment a filename holds a space or a glob character, an unquoted expansion makes a single argument unfold into three. The `[[ ... ]]` form is generally preferable to `[ ... ]` when POSIX portability is not required — it handles empty variables without breaking, supports regular expressions, and behaves more predictably. Bash arithmetic with `$((...))` understands only integers, so fractional math should be delegated to `bc` or `awk` rather than wrestled with inside Bash. The cheatsheet groups all of this into Basics, Variables, Conditionals, Loops, Arrays, Functions, and I/O so the right section is one click away.
- 60+ Bash scripting snippets
- Variable expansions and defaults
- Conditionals and test operators
- Arrays (indexed and associative)
- Functions and arguments
- Pipes and redirection
Free. No signup. Your inputs stay in your browser. Ads via Google AdSense (consent required).
By Marco B. ·