Catalog / Bash Cheatsheet
Bash Cheatsheet
A quick reference for Bash scripting, covering essential syntax, commands, and best practices for writing efficient and robust scripts.
Basics & Syntax
Getting Started
Shebang:
This line specifies the interpreter for the script. |
Variables:
Variable assignment and usage. Always quote variables unless you need wildcard expansion or command substitution. |
String Quotes:
Double quotes allow variable interpolation, single quotes do not. |
Command Substitution:
Executes a command and inserts its output. |
Conditional Execution:
Execute commands based on the success or failure of previous commands. |
Strict Mode:
Enable strict mode to catch errors and improve script reliability. |
Comments
Single-line comment:
|
Multi-line comment:
|
Brace Expansion
|
Same as |
|
Same as |
|
Same as |
|
Same as |
Parameter Expansion & Manipulation
Parameter Expansion
Basics:
|
More basics:
|
Path manipulation:
|
More path manipulation:
|
More string manipulation:
|
Substitution
|
Remove suffix |
|
Remove prefix |
|
Remove long suffix |
|
Remove long prefix |
|
Replace first match |
|
Replace all |
String Manipulation
Case conversion:
|
More case conversion:
|
Default values
|
|
|
Set |
|
|
|
Show error message and exit if |
Loops & Functions
Loops
Basic
|
C-style
|
Ranges in
|
Ranges with step size:
|
Reading lines from a file:
|
Infinite loop:
|
Functions
Defining a function:
Alternative syntax:
|
Calling a function:
|
Returning values:
|
Raising errors:
|
Function Arguments:
|
Arguments
|
Number of arguments |
|
All positional arguments (as a single word) |
|
All positional arguments (as separate strings) |
|
First argument |
|
Last argument of the previous command |
Conditionals, Arrays, Dictionaries
Conditionals
String conditions:
|
Numeric conditions:
|
File conditions:
|
Conditions
|
Empty string |
|
Not empty string |
|
Equal |
|
Not Equal |
|
Equal |
|
Not equal |
Arrays
Defining an array:
|
Accessing array elements:
|
Array operations:
|
Iterate array:
|
Dictionaries
Defining a dictionary:
|
Accessing dictionary elements:
|
Dictionary operations:
|
Iterating dictionary (values):
|
Iterating dictionary (keys):
|
Options & Miscellaneous
Options
Setting options:
|
Glob options:
|
History
Commands:
|
Expansions:
|
Operations:
|
Miscellaneous
Numeric calculations:
|
Redirection:
|
Inspecting commands:
|
Case/switch statment:
|
Go to the previous directory:
|
Special Variables
|
Exit status of last task |
|
PID of last background task |
|
PID of shell |
|
Filename of the shell script |
|
Last argument of the previous command |