Cheatsheet: Bash scripting
Last updated 2026-06-21
Script basics
Start a script with a Bash shebang
Fail fast on errors, unset variables, and pipeline failures
Declare and read a variable
Use command substitution to capture command output
Exit with a success or failure status
Arguments and functions
Read positional arguments
Loop over all arguments safely
Check the number of arguments
Define and call a function
Conditionals and tests
Use an if statement with Bash test syntax
Combine string and file tests
Use numeric comparisons
Branch with a case statement
Check the previous command exit code
Loops and data
Iterate over files with a for loop
Read a file line by line
Use arrays and expand elements safely
Use common string parameter expansions
Do integer arithmetic
Input and output
Redirect standard output and standard error
Append output and merge errors into the same file
Send a multi-line here-doc to a command
See also: