Bash Scripting Cheatsheet
The Bash syntax you need to write real scripts — beyond typing commands interactively. Pair it with the Linux commands cheatsheet for the commands themselves.
Variables
Assign a variable — no spaces around the equals sign.
Use a variable; braces help when concatenating.
Capture command output into a value.
Script arguments; $@ is all of them.
Exit status of the last command (0 = success).
Conditionals
Basic if statement.
True if file exists and is a regular file.
True if the string is empty.
Numeric equality; also -lt, -gt, -ge.
Run b if a succeeds / if a fails.
Loops
Loop over matching files.
Loop over a numeric range.
Read a file line by line.
Loop until the condition is true.
Functions
Define a function taking arguments.
Return an exit status from a function.
Declare a variable local to the function.
Strings & expansion
Length of the string.
Use default if var is unset or empty.
Replace first occurrence of a substring.
Strip everything up to the last slash (basename).
Safety
Exit immediately if any command fails.
Error on use of an unset variable.
A pipeline fails if any part fails.
Run a function when the script exits.