Write robust bash scripts for automation and system administration.
Category: Linux
Script Structure
#!/bin/bash
set -euo pipefail # exit on error, undefined vars, pipe failures
IFS=$'\n\t' # safer word splitting
# Variables
NAME="world"
echo "Hello, $NAME"
Conditionals
if [[ -f /etc/passwd ]]; then
echo "File exists"
elif [[ -d /tmp ]]; then
echo "Directory exists"
else
echo "Neither"
fi
# String comparison
if [[ "$USER" == "root" ]]; then
echo "Running as root"
fi
# Numeric comparison
COUNT=5
if (( COUNT > 3 )); then
echo "Count is greater than 3"
fi
Loops
# For loop over list
for server in web01 web02 db01; do
echo "Checking $server..."
ping -c 1 "$server" &>/dev/null && echo " UP" || echo " DOWN"
done
# While loop
COUNT=0
while (( COUNT < 5 )); do
echo "Count: $COUNT"
(( COUNT++ ))
done
# Loop over files
for f in /etc/*.conf; do
echo "Config: $f"
done
Functions
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a /var/log/myscript.log
}
check_service() {
local svc="$1"
systemctl is-active --quiet "$svc" && log "$svc is running" || log "WARNING: $svc is down"
}
check_service nginx
check_service mysql
Error Handling
cleanup() {
echo "Cleaning up..."
rm -f /tmp/myscript.lock
}
trap cleanup EXIT ERR
# Lock file to prevent duplicate runs
if [[ -f /tmp/myscript.lock ]]; then
echo "Script already running"
exit 1
fi
touch /tmp/myscript.lock
Script Arguments
#!/bin/bash
# Usage: ./deploy.sh staging|production
ENV="${1:-staging}" # default to staging
case "$ENV" in
staging) HOST="staging.example.com" ;;
production) HOST="prod.example.com" ;;
*) echo "Usage: $0 staging|production"; exit 1 ;;
esac
echo "Deploying to $HOST..."