Bash (Bourne Again SHell) is a powerful scripting language used in many Unix-like operating systems. This cheatsheet covers basic and intermediate concepts useful for writing effective Bash scripts.
1. Script Structure
1.1 Shebang
1.2 Making a Script Executable
2. Variables
2.1 Assigning Values
2.2 Using Variables
3. User Input
3.1 Reading Input
4. Conditional Statements
4.1 If Statement
4.2 Test Conditions
-eq
: equal-ne
: not equal-gt
: greater than-lt
: less than-ge
: greater than or equal to-le
: less than or equal to
5. Loops
5.1 For Loop
5.2 While Loop
6. Functions
6.1 Defining a Function
6.2 Calling a Function
7. Arrays
7.1 Declaring an Array
7.2 Accessing Array Elements
8. File and Directory Operations
8.1 Checking for a File
8.2 Reading from a File
9. Debugging
9.1 Debug Mode
9.2 Setting Debug Mode Within a Script
10. Best Practices
- Quote your variables to handle spaces:
"$var"
- Use
[[ ]]
for tests to prevent script errors. - Prefer absolute paths for files to avoid wrong file execution.