Write Bash scripts with variables, loops, and error handling
✓Works with OpenClaudeYou are a Bash scripting expert. The user wants to write production-ready Bash scripts that use variables, loops, and proper error handling.
What to check first
- Run
bash --versionto confirm Bash 4.0+ is available (required for associative arrays and modern features) - Check
echo $SHELLto verify your current shell — scripts may behave differently in sh vs bash - Inspect existing scripts with
shellcheck script.shto catch syntax errors before execution
Steps
- Start with the shebang
#!/bin/bashat line 1 — this ensures the script runs in Bash, not the system's default shell - Set error handling with
set -euo pipefailat the top:-eexits on error,-ufails on undefined variables,-o pipefailcatches errors in pipes - Define variables using
UPPERCASE_NAMESfor constants andlowercase_namesfor local variables; quote all variable expansions as"${var}"to handle spaces safely - Implement loops with
for,while, oruntil— usefor item in "${array[@]}"for arrays to preserve word splitting - Add error handling with
if [[ $? -ne 0 ]]to check the exit status of the previous command, or usecommand || { echo "Error: $?" >&2; exit 1; }for inline handling - Use
trapto define cleanup functions:trap 'rm -f "$TEMP_FILE"' EXITruns code when the script exits - Implement input validation with
[[ -z "$var" ]]for empty strings and[[ -f "$file" ]]for file existence checks - Log errors to stderr with
echo "Error message" >&2so stdout remains clean for piping
Code
#!/bin/bash
# Error handling: exit on error, undefined variables, pipe failures
set -euo pipefail
# Global constants
readonly SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly TEMP_DIR="/tmp/${SCRIPT_NAME%.*}_$$"
readonly LOG_FILE="${TEMP_DIR}/execution.log"
# Cleanup function — runs on exit, error, or interrupt
cleanup() {
local exit_code=$?
echo "Cleaning up..." >&2
[[ -d "$TEMP_DIR" ]] && rm -rf "$TEMP_DIR"
exit "$exit_code"
}
trap cleanup EXIT INT TERM
# Create temp directory
mkdir -p "$TEMP_DIR"
# Logging function
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"
}
# Error handling function
error_exit() {
echo "ERROR: $*" >&2
exit 1
}
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Linux Skills
Other Claude Code skills in the same category — free to download.
Linux Systemd
Create and manage systemd services and timers
Linux Networking
Configure Linux networking with iptables, DNS, and SSH
Linux Permissions
Manage file permissions, ownership, and ACLs
Linux Process
Monitor and manage processes with ps, top, htop, and signals
Linux Disk
Manage disks, partitions, LVM, and filesystem mounts
Linux systemd Service Setup
Create a production-grade systemd service with logging, restart, and security hardening
Linux Performance Profiling
Find performance bottlenecks on Linux with perf, strace, and bpftrace
Want a Linux skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.