Bash Scripting — Automate Your Workflow
Advertisement
Bash Scripting — Automate Your Workflow
Automate DevOps tasks with Bash scripts for efficient workflow.
Basic Script
#!/bin/bash
set -e # Exit on error
echo "Starting deployment..."
# Variables
ENV=${1:-production}
VERSION=${2:-latest}
# Check prerequisites
if [ ! -f "Dockerfile" ]; then
echo "Dockerfile not found"
exit 1
fi
echo "Deploying version $VERSION to $ENV"
Loops and Conditionals
# For loop
for file in *.txt; do
echo "Processing $file"
done
# While loop
while [ $count -lt 10 ]; do
echo $count
((count++))
done
# If conditions
if [ -f "file.txt" ]; then
echo "File exists"
elif [ -d "directory" ]; then
echo "Directory exists"
else
echo "Not found"
fi
# Case statement
case $ENV in
production)
echo "Deploying to production"
;;
staging)
echo "Deploying to staging"
;;
*)
echo "Unknown environment"
;;
esac
Functions
deploy() {
local env=$1
local version=$2
echo "Deploying $version to $env"
# Deployment logic
return 0
}
# Call function
deploy "production" "1.0.0"
Error Handling
set -e # Exit on error
set -u # Error on undefined variables
set -o pipefail # Pipe fails on any error
trap 'echo "Error on line $LINENO"' ERR
command || { echo "Command failed"; exit 1; }
FAQ
Q: What's the best way to handle errors in Bash? A: Use set -e for immediate exit on error, or explicitly check return codes.
Advertisement