Scripts¶
Automation scripts for common development tasks.
Overview¶
Keep commonly used scripts in a scripts/ directory at the project root.
scripts/
├── setup.sh # Initial project setup
├── dev.sh # Start development environment
├── reset-db.sh # Reset database
├── seed.sh # Seed test data
├── test.sh # Run tests with coverage
├── deploy.sh # Deployment script
└── cleanup.sh # Clean temporary files
Script Best Practices¶
Header Template¶
#!/bin/bash
#
# Description: Brief description of what this script does
# Usage: ./scripts/script-name.sh [options]
#
set -euo pipefail # Exit on error, undefined var, pipe failure
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
# Logging functions
info() { echo -e "${GREEN}[INFO]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1" >&2; exit 1; }
Error Handling¶
# Exit on any error
set -e
# Exit on undefined variable
set -u
# Exit on pipe failure
set -o pipefail
# Cleanup on exit
cleanup() {
echo "Cleaning up..."
# Remove temp files, kill background processes, etc.
}
trap cleanup EXIT
# Cleanup on error
trap 'error "Script failed on line $LINENO"' ERR
Argument Parsing¶
#!/bin/bash
usage() {
echo "Usage: $0 [-f|--force] [-v|--verbose] <environment>"
echo " environment: dev, staging, or production"
exit 1
}
FORCE=false
VERBOSE=false
ENVIRONMENT=""
while [[ $# -gt 0 ]]; do
case $1 in
-f|--force)
FORCE=true
shift
;;
-v|--verbose)
VERBOSE=true
shift
;;
-h|--help)
usage
;;
-*)
echo "Unknown option: $1"
usage
;;
*)
ENVIRONMENT="$1"
shift
;;
esac
done
if [[ -z "$ENVIRONMENT" ]]; then
usage
fi
Confirmation Prompts¶
confirm() {
local message="${1:-Are you sure?}"
read -p "$message [y/N] " response
case "$response" in
[yY][eE][sS]|[yY])
return 0
;;
*)
return 1
;;
esac
}
# Usage
if confirm "Reset database? This will delete all data."; then
echo "Resetting..."
else
echo "Aborted."
exit 0
fi
Related Documentation¶
- Common Scripts — Ready-to-use script templates