Bash40 commands
Bash Scripting Cheat Sheet
Essential Bash scripting patterns — variables, conditionals, loops, functions, string manipulation, and error handling.
Variables & Strings
| Command | Description |
|---|---|
| Assign variable (no spaces around =) |
| Use variable in string |
| Default value if unset |
| String length |
| Uppercase |
| Lowercase |
| Replace first occurrence |
| Replace all occurrences |
| Command substitution |
| Declare constant |
Conditionals
| Command | Description |
|---|---|
| Check if file exists |
| Check if directory exists |
| Check if string is empty |
| Check if string is not empty |
| String equality |
| Numeric comparison |
| Check command exit status |
| Ternary-style one-liner |
Loops
| Command | Description |
|---|---|
| Loop over files |
| Loop over range |
| Read file line by line |
| Infinite loop with delay |
| Loop over script arguments |
Functions
| Command | Description |
|---|---|
| Define function |
| Local variable in function |
| Return exit code from function |
| Capture function output |
Error Handling
| Command | Description |
|---|---|
| Exit on first error |
| Error on undefined variables |
| Catch errors in pipes |
| Strict mode (combine all three) |
| Run cleanup on exit |
| Handle command failure |
Arrays & I/O
| Command | Description |
|---|---|
| Declare array |
| Access first element |
| All elements |
| Array length |
| Prompt for input |
| Redirect stdout and stderr |
| Suppress error output |