Essential Bash Script Building Blocks
A collection of essential bash script building blocks and best practices for robust shell scripting.
Start your bash script with the proper shebang to ensure portability:
#!/usr/bin/env bash
Start your bash script with the proper shebang to ensure portability:
#!/usr/bin/env bash
Use strict mode for safer script execution and better error handling:
set -euo pipefail
This ensures:
-e: Exit immediately if a command exits with a non-zero status-u: Treat unset variables as an error-o pipefail: Return the exit status of the last command in a pipeline that failed
Check if strings are empty or contain values:
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
fi
Iterate over a range of numbers efficiently:
for i in {1..5}; do
echo "Processing item: $i"
done
Create reusable functions with proper parameter handling:
function process_file() {
local filename="$1"
echo "Processing file: $filename"
# Function logic here
}
# Call the function
process_file "example.txt"