Table of Contents
- Bash Conditionals Examples
- Bash Error Handling
- 1. Using
$?(Exit Status) - 2.
setBuilt-In Command - 3.
trapCommand - 4. Using
||(OR) for Fallback - 5. Using
ifStatements - 6. Using Functions for Error Handling
- 7. Combining
pipefailwith Pipelines - 8. Redirecting Errors to a Log File
- 9. Retry Logic
- 10. Error Messages with
>&2 - Summary of Error Handling Techniques:
- 11. Parameter expansion in bash
- 1. Using
- Bash Shortcuts Cheat Sheet
- Bash Arrays (Indexed and Associative)
- 1. What Is a Bash Array?
- 2. Indexed Arrays (Most Common)
- 3. Accessing Array Elements
- 4. Iterating Over Arrays
- 5. Adding and Removing Elements
- 6. Associative Arrays (Key/Value)
- 7. Iterating Associative Arrays
- 8. Reading Command Output Into Arrays
- 9. Arrays From Globs
- 10. Passing Arrays to Functions
- 11. Common Real-World Patterns
- 12. Sorting Arrays
- 13. Copying Arrays
- 14. Common Mistakes (Very Important)
- 15. Quick Reference Cheat Sheet
- Summary
Bash Conditionals Examples
You can find a link to the GNU manual below.
Reference:
1. If-Else Conditional
Syntax:
if [ condition ]; then
# Code to execute if condition is true
elif [ another_condition ]; then
# Code to execute if another_condition is true
else
# Code to execute if none of the above conditions are true
fi
Example:
#!/bin/bash
num=10
if [ $num -gt 5 ]; then
echo "$num is greater than 5"
elif [ $num -eq 5 ]; then
echo "$num is equal to 5"
else
echo "$num is less than 5"
fi
2. Comparison Operators
Numeric Comparisons:
| Operator | Description | Example |
|---|---|---|
-eq | Equal to | [ $a -eq $b ] |
-ne | Not equal to | [ $a -ne $b ] |
-gt | Greater than | [ $a -gt $b ] |
-ge | Greater than or equal to | [ $a -ge $b ] |
-lt | Less than | [ $a -lt $b ] |
-le | Less than or equal to | [ $a -le $b ] |
String Comparisons:
| Operator | Description | Example |
|---|---|---|
= | Strings are equal | [ "$a" = "$b" ] |
!= | Strings are not equal | [ "$a" != "$b" ] |
< | String is less than (lexicographically) | [ "$a" \< "$b" ] |
> | String is greater than | [ "$a" \> "$b" ] |
-z | String is empty | [ -z "$a" ] |
-n | String is not empty | [ -n "$a" ] |
3. Logical Operators
| Operator | Description | Example |
|---|---|---|
! | Logical NOT | [ ! condition ] |
&& | Logical AND | [ condition1 ] && [ condition2 ] |
|| | Logical OR | [ condition1 ] || [ condition2 ] |
Example:
is_admin=true
is_logged_in=true
if [ "$is_admin" = "true" ] && [ "$is_logged_in" = "true" ]; then
echo "Access granted"
else
echo "Access denied"
fi
4. Using [[ for Advanced Conditions
[[ is more flexible than [. It supports pattern matching and avoids certain pitfalls.
Example:
str="Hello"
if [[ $str == H* ]]; then
echo "String starts with H"
fi
5. Ternary statement
# Will assign variable to value of $2 if present , if not , /tmp will be used as the value
FILE_LOC=${2:-/tmp}
5. Case Statement
Syntax:
case $variable in
pattern1)
# Code to execute if pattern1 matches
;;
pattern2)
# Code to execute if pattern2 matches
;;
*)
# Default case
;;
esac
Example:
#!/bin/bash
fruit="apple"
case $fruit in
apple)
echo "It's an apple!"
;;
banana)
echo "It's a banana!"
;;
*)
echo "Unknown fruit."
;;
esac
6. File Tests
| Operator | Description | Example |
|---|---|---|
-e | File exists | [ -e file ] |
-f | File exists and is a regular file | [ -f file ] |
-d | Directory exists | [ -d directory ] |
-r | File is readable | [ -r file ] |
-w | File is writable | [ -w file ] |
-x | File is executable | [ -x file ] |
-s | File is not empty | [ -s file ] |
Example:
#!/bin/bash
file="example.txt"
if [ -f "$file" ]; then
echo "$file exists and is a regular file."
else
echo "$file does not exist."
fi
Summary
- Use
if,case, and logical operators for branching. - Use
[ ]or[[ ]]for conditions. - Combine numeric, string, and file tests as needed.
These tools are the foundation of Bash scripting logic.
Bash Error Handling
1. Using $? (Exit Status)
Every command in Bash returns an exit status:
0: Indicates success.- Non-zero: Indicates failure.
Example:
#!/bin/bash
cp file.txt /nonexistent-directory
if [ $? -ne 0 ]; then
echo "Error: Failed to copy file."
fi
2. set Built-In Command
set -e: Exit on Error
Automatically exits the script if a command returns a non-zero exit status.
#!/bin/bash
set -e
echo "This runs."
cp file.txt /nonexistent-directory # Causes the script to exit
echo "This will not run."
set -u: Treat Undefined Variables as Errors
Triggers an error if an undefined variable is used.
#!/bin/bash
set -u
echo "This is defined: $DEFINED_VAR"
Common Combination:
set -euo pipefail
-e: Exit on error.-u: Treat undefined variables as errors.pipefail: Ensures the script fails if any command in a pipeline fails.
3. trap Command
The trap command lets you handle signals and cleanup tasks.
Example: Cleanup on Exit
#!/bin/bash
trap "echo 'An error occurred. Exiting...'; exit 1" ERR
cp file.txt /nonexistent-directory # Error triggers trap
echo "This will not run."
Example: Cleanup Temporary Files
#!/bin/bash
trap "rm -f /tmp/tempfile; echo 'Cleaned up.'" EXIT
touch /tmp/tempfile
echo "Doing work..."
4. Using || (OR) for Fallback
Run an alternate command if the first one fails.
Example:
#!/bin/bash
mkdir /example-directory || echo "Failed to create directory."
5. Using if Statements
Manually check the success of commands.
Example:
#!/bin/bash
if cp file.txt /nonexistent-directory; then
echo "File copied successfully."
else
echo "Failed to copy file."
fi
6. Using Functions for Error Handling
Encapsulate commands and error handling logic into functions.
Example:
#!/bin/bash
error_exit() {
echo "Error: $1"
exit 1
}
cp file.txt /nonexistent-directory || error_exit "Failed to copy file."
7. Combining pipefail with Pipelines
By default, only the last command in a pipeline affects the exit status. Use set -o pipefail to fail the pipeline if any command fails.
Example:
#!/bin/bash
set -o pipefail
cat file.txt | grep "text" | sort || echo "Pipeline failed."
8. Redirecting Errors to a Log File
Redirect error messages to a file for later inspection.
Example:
#!/bin/bash
command 2> error.log
2>: Redirectsstderr(standard error).
9. Retry Logic
Retry a command if it fails.
Example:
#!/bin/bash
for i in {1..3}; do
command && break || echo "Attempt $i failed."
sleep 1
done
10. Error Messages with >&2
Send error messages to stderr.
Example:
#!/bin/bash
echo "This is an error message." >&2
Summary of Error Handling Techniques:
- Use
$?to check the exit status of commands. - Use
set -euo pipefailfor more robust scripts. - Use
trapto handle unexpected errors and perform cleanup. - Redirect
stderrto log files for debugging.
These techniques can help make your Bash scripts more robust and capable of handling unexpected conditions.
11. Parameter expansion in bash
Parameter expansion allows you to modify and manipulate the values of variables.
Bash Shortcuts Cheat Sheet
Navigating the Command Line
Ctrl+A: Move to the beginning of the line.Ctrl+E: Move to the end of the line.Alt+F: Move forward one word.Alt+B: Move backward one word.Ctrl+L: Clear the screen (same asclearcommand).
Editing Commands
Ctrl+U: Cut (delete) from the cursor to the beginning of the line.Ctrl+K: Cut (delete) from the cursor to the end of the line.Ctrl+W: Cut (delete) the word before the cursor.Alt+D: Cut (delete) the word after the cursor.Ctrl+Y: Paste the last cut text (yank).Ctrl+T: Swap the last two characters before the cursor.Alt+T: Swap the last two words before the cursor.Ctrl+_: Undo the last editing action.
Searching and Reusing Commands
Ctrl+R: Reverse search through command history.Ctrl+S: Forward search through command history (if enabled).Ctrl+G: Cancel search in history.Up Arrow: Scroll backward through command history.Down Arrow: Scroll forward through command history.!!: Repeat the last command.!<n>: Execute command number<n>from history.!<prefix>: Execute the most recent command starting with<prefix>.
Controlling Processes
Ctrl+C: Kill the current process.Ctrl+Z: Suspend the current process.jobs: List suspended or background processes.fg: Resume the most recent suspended process in the foreground.bg: Resume the most recent suspended process in the background.
Moving and Manipulating Text
Ctrl+Left Arrow: Move to the beginning of the previous word (if enabled).Ctrl+Right Arrow: Move to the beginning of the next word (if enabled).Alt+.: Insert the last argument of the previous command.
Shell Features
Ctrl+D: Log out of the current shell session.Ctrl+P: Scroll backward through history (same as up arrow).Ctrl+N: Scroll forward through history (same as down arrow).Ctrl+X Ctrl+E: Open the current command in your default editor.Tab: Autocomplete files, directories, or commands.
Terminal Control
Ctrl+S: Pause terminal output.Ctrl+Q: Resume terminal output.Ctrl+Z: Suspend the current foreground process.Ctrl+D: Send EOF (end of file) to the terminal, often used to log out or close the terminal.
Special Characters
Ctrl+V: Insert the next character literally (e.g., typeCtrl+V Tabto insert a literal Tab character).Ctrl+O: Execute the command and bring the next one from history.
Debugging
Ctrl+X Ctrl+V: Print the version of Bash.
Miscellaneous
Ctrl+G: Exit the current editing mode or cancel a command.
Bash Arrays (Indexed and Associative)
This page documents practical, exam-safe, and script-ready usage of arrays in Bash.
Covers:
- Indexed arrays
- Associative arrays
- Common patterns
- Pitfalls
- RHCSA / real-world scripting tips
Targeted for Bash 4+ (RHEL / Alma / Rocky / Debian).
1. What Is a Bash Array?
An array allows a variable to hold multiple values.
Bash supports:
- Indexed arrays (numeric index)
- Associative arrays (key/value)
2. Indexed Arrays (Most Common)
Declare and Assign
arr=(one two three)
Explicit indices:
arr[0]="one"
arr[1]="two"
arr[2]="three"
3. Accessing Array Elements
echo "${arr[0]}" # one
echo "${arr[@]}" # all elements
echo "${arr[*]}" # all elements (single word)
Length
echo "${#arr[@]}" # number of elements
4. Iterating Over Arrays
Safe Loop (Recommended)
for item in "${arr[@]}"; do
echo "$item"
done
Index-Based Loop
for i in "${!arr[@]}"; do
echo "$i => ${arr[$i]}"
done
5. Adding and Removing Elements
Append
arr+=(four)
Remove Element
unset arr[1]
(Indices are not reindexed automatically.)
6. Associative Arrays (Key/Value)
Requires Bash 4+
Declare
declare -A ports
Assign
ports[http]=80
ports[https]=443
ports[ssh]=22
Access
echo "${ports[http]}"
7. Iterating Associative Arrays
for key in "${!ports[@]}"; do
echo "$key => ${ports[$key]}"
done
8. Reading Command Output Into Arrays
Using mapfile / readarray (Best)
mapfile -t users < <(cut -d: -f1 /etc/passwd)
Using read (Legacy)
IFS=$'\n' read -r -d '' -a users < <(command)
9. Arrays From Globs
files=(/var/log/*.log)
Check before use:
(( ${#files[@]} )) || echo "No files found"
10. Passing Arrays to Functions
Function Definition
print_array() {
local arr=("$@")
for i in "${arr[@]}"; do
echo "$i"
done
}
Call
print_array "${arr[@]}"
11. Common Real-World Patterns
Loop Over Disks
disks=(/dev/sdb /dev/sdc)
for d in "${disks[@]}"; do
parted -s "$d" print
done
Parallel Arrays (Avoid if Possible)
users=(alice bob)
uids=(1001 1002)
Prefer associative arrays instead.
12. Sorting Arrays
sorted=( $(printf "%s\n" "${arr[@]}" | sort) )
13. Copying Arrays
copy=("${arr[@]}")
14. Common Mistakes (Very Important)
❌ Using ${arr} instead of ${arr[@]}
❌ Forgetting quotes around ${arr[@]}
❌ Assuming indices are contiguous after unset
❌ Using associative arrays without declare -A
❌ Running scripts with /bin/sh instead of bash
15. Quick Reference Cheat Sheet
arr=(a b c) # declare indexed
arr+=(d) # append
${arr[0]} # element
${arr[@]} # all elements
${#arr[@]} # length
unset arr[1] # remove element
declare -A map # associative
map[key]=value # assign
${map[key]} # access
${!map[@]} # keys
Summary
- Use arrays to avoid word-splitting bugs
- Always quote
"${array[@]}" - Prefer associative arrays over parallel arrays
mapfileis the cleanest way to populate arrays- Arrays are essential for safe Bash automation
Suitable for RHCSA prep, production scripting, and personal wiki use.