Catalog / Bash Scripting Essentials Cheatsheet
Bash Scripting Essentials Cheatsheet
A concise reference for Bash scripting, covering essential syntax, commands, and best practices. Includes variables, loops, conditionals, functions, and more, to help you write effective and maintainable scripts.
Basics & Variables
Script Structure
Every bash script starts with a shebang line, specifying the interpreter.
|
Use comments to explain your code.
|
Best practice: use strict mode to catch errors early.
|
Variables
Defining a variable: |
|
Accessing a variable: |
|
String quotes: |
|
Variable scope (local): |
|
Readonly variables: |
|
Brace Expansion
Generate combinations of strings.
|
Loops & Conditionals
Loops
Basic
|
C-style
|
Looping through a range:
|
Looping with step size:
|
Reading lines from a file:
|
Infinite loop:
|
Conditionals
Basic |
|
Using |
|
Numeric conditions: |
|
File existence check: |
|
Case Statements
|
Functions & Arrays
Functions
Defining a function: |
|
Calling a function: |
|
Returning values: |
|
Raising errors: |
|
Passing arguments: |
|
Arrays
Defining arrays:
|
Accessing elements:
|
Iterating through elements:
|
Getting array length:
|
Adding elements:
|
Parameter Expansion & Redirection
Parameter Expansion
Basics:
|
String manipulation:
|
Default values:
|
Redirection
Stdout to file: |
|
Stdout to file (append): |
|
Stderr to file: |
|
Stderr to stdout: |
|
Both stdout and stderr to file: |
|
Feed file to stdin: |
|
Advanced Features
History Expansion
Show history:
|
Expand last parameter of most recent command:
|
Expand all parameters of most recent command:
|
Expand nth most recent command:
|
Execute last command again:
|
Replace in last command:
|
Options and Globbing
Disable file overwriting: |
|
Exit on error: |
|
Fail on pipe errors: |
|
Unset variables are errors: |
|
Wildcards match dotfiles: |
|
Recursive globbing |
|
String Manipulation
Uppercase and Lowercase Transformations:
|
Transforming strings using
|
Getting the directory of the script:
|