Catalog / Bash Scripting Cheatsheet
Bash Scripting Cheatsheet
A comprehensive cheat sheet covering Bash scripting essentials, from basic syntax to advanced techniques. Includes variables, functions, conditionals, loops, and more, with practical examples for quick reference.
Basics & Variables
Script Header & Execution
Shebang:
Recommended header for portability. Specifies the interpreter for the script. |
Execution:
Make script executable: |
Exit Status: |
Comments:
|
Variables
Declaration: |
|
Usage: |
Always quote variables to prevent word splitting and globbing. |
String Quotes: |
|
Environment Variables: |
|
Unsetting Variables: |
|
Command Substitution
Capture output of a command:
|
Backticks (obsolescent):
|
Functions & Conditionals
Functions
Definition: |
|
Calling: |
|
Returning Values: |
|
Raising Errors: |
|
Arguments: |
|
Special Parameters: |
|
Conditionals
Basic Syntax: |
|
String Conditions: |
|
Numeric Conditions: |
|
File Conditions: |
|
Combining Conditions: |
|
Example: |
|
Loops & Arrays
Loops
Basic For Loop: |
|
C-like For Loop: |
|
Ranges: |
|
Reading Lines: |
|
Forever Loop: |
|
Arrays
Defining Arrays: |
|
Accessing Elements: |
|
Array Length: |
|
Range/Slice: |
|
Keys: |
|
Operations: |
|
Iteration: |
|
Dictionaries & Options
Dictionaries (Associative Arrays)
Defining Dictionaries: |
|
Accessing Values: |
|
Accessing Keys: |
|
Number of Elements: |
|
Deleting Elements: |
|
Iteration (Values): |
|
Iteration (Keys): |
|
Options (set)
|
Avoid overlaying files (e.g., |
|
Exit immediately if a command exits with a non-zero status (helps prevent cascading errors). |
|
If a command in a pipeline fails, the pipeline’s exit status is that of the failed command. |
|
Attempting to use an unset variable results in an error, exposing potential bugs. |
Glob Options (shopt)
|
If a glob pattern doesn’t match any files, it’s removed from the argument list (e.g., |
|
If a glob pattern doesn’t match, an error is thrown. |
|
Glob patterns are case-insensitive. |
|
Wildcards match dotfiles (e.g., |
|
Allows |
Redirection and miscellaneous
Redirection
|
|
|
|
|
|
|
|
Heredoc
|
|
History expansions
|
Execute last command again |
|
Expand last parameter of most recent command |
|
Expand all parameters of most recent command |
|
Expand nth most recent command |
|
Expand nth command in history |
|
Expand most recent invocation of command |