Last updated
Bash Script Structure
A well-structured Bash script starts with a shebang line, sets safety options,
defines variables and functions, and handles errors gracefully.
The shebang (#!/bin/bash) tells the OS which interpreter to use.
Safety options like set -euo pipefail make scripts fail fast
on errors instead of silently continuing.
Bash Script Template
Bash
#!/usr/bin/env bash
set -euo pipefail
IFS=$'
'
# Script metadata
readonly SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Colors for output
RED='[0;31m'; GREEN='[0;32m'; YELLOW='[1;33m'; NC='[0m'
log() { echo -e "${GREEN}[INFO]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*" >&2; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; exit 1; }
usage() {
cat <<EOF
Usage: $SCRIPT_NAME [OPTIONS] <argument>
Options:
-h, --help Show this help
-v, --verbose Enable verbose output
EOF
}
main() {
local verbose=false
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help) usage; exit 0 ;;
-v|--verbose) verbose=true; shift ;;
*) break ;;
esac
done
[[ $# -eq 0 ]] && error "No argument provided"
log "Processing: $1"
}
main "$@"
Common Bash Patterns
| Pattern | Code |
|---|---|
| Check if file exists | [[ -f "$file" ]] |
| Check if directory exists | [[ -d "$dir" ]] |
| Check if command exists | command -v git &>/dev/null |
| Default value | ${VAR:-default} |
| String contains | [[ "$str" == *"substr"* ]] |