Script Utility Patterns
Script Utility Patterns
When to Use This Skill
Use this skill when implementing script utility patterns patterns in your codebase.
How to Use This Skill
- Review the patterns and examples below
- Apply the relevant patterns to your implementation
- Follow the best practices outlined in this skill
Level 1: Quick Reference (Under 500 tokens)
Shell Script Template
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'
log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
cleanup() {
# Cleanup logic
:
}
trap cleanup EXIT
main() {
log_info "Starting script..."
# Main logic
}
main "$@"
npm Scripts Organization
{
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"test": "vitest",
"test:coverage": "vitest --coverage",
"lint": "eslint src/",
"lint:fix": "eslint src/ --fix",
"format": "prettier --write src/"
}
}
Level 2: Implementation Details (Under 2000 tokens)
Makefile Patterns
.PHONY: all build test clean
SHELL := /bin/bash
.DEFAULT_GOAL := help
help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}'
build: ## Build the project
cargo build --release
test: ## Run tests
cargo test
clean: ## Clean build artifacts
cargo clean
docker-build: ## Build Docker image
docker build -t myapp:latest .
Cross-Platform Script Detection
detect_os() {
case "$(uname -s)" in
Linux*) echo "linux" ;;
Darwin*) echo "macos" ;;
MINGW*|MSYS*|CYGWIN*) echo "windows" ;;
*) echo "unknown" ;;
esac
}
detect_arch() {
case "$(uname -m)" in
x86_64|amd64) echo "x64" ;;
arm64|aarch64) echo "arm64" ;;
*) echo "unknown" ;;
esac
}
Level 3: Complete Reference (Full tokens)
Python Script Runner
#!/usr/bin/env python3
import argparse
import subprocess
import sys
from pathlib import Path
def run_command(cmd: list[str], cwd: Path | None = None) -> int:
result = subprocess.run(cmd, cwd=cwd)
return result.returncode
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--verbose', '-v', action='store_true')
args = parser.parse_args()
scripts_dir = Path(__file__).parent
if args.verbose:
print(f"Running from: {scripts_dir}")
return run_command(['npm', 'test'], cwd=scripts_dir.parent)
if __name__ == '__main__':
sys.exit(main())
Best Practices:
- Use
set -euo pipefailin bash scripts - Implement cleanup with trap
- Provide help/usage documentation
- Support both interactive and CI modes
- Use cross-platform detection for portability
Success Output
When successful, this skill MUST output:
✅ SKILL COMPLETE: script-utility-patterns
Completed:
- [x] Shell script template applied with error handling
- [x] npm scripts organized by category
- [x] Makefile with help target created
- [x] Cross-platform detection implemented
- [x] Python script runner with argparse
- [x] Cleanup trap handlers configured
Outputs:
- Shell scripts with set -euo pipefail
- package.json with organized npm scripts
- Makefile with self-documenting help
- Platform detection functions
- Python scripts with proper error handling
Completion Checklist
Before marking this skill as complete, verify:
- Shell scripts use
set -euo pipefail - Cleanup functions registered with trap EXIT
- Log functions (log_info, log_error) implemented
- npm scripts organized by purpose (dev, build, test, lint)
- Makefile has help target showing all commands
- Cross-platform detection for OS and architecture
- Python scripts use argparse for CLI arguments
- All scripts have usage documentation
- Scripts work in both interactive and CI environments
- Scripts are executable (chmod +x)
Failure Indicators
This skill has FAILED if:
- ❌ Shell scripts missing error handling (no set -euo pipefail)
- ❌ Scripts fail silently instead of exiting with error codes
- ❌ No cleanup handlers (temp files left behind)
- ❌ npm scripts have no organization or naming convention
- ❌ Makefile lacks help/documentation target
- ❌ Scripts only work on one platform (no cross-platform support)
- ❌ Python scripts use sys.argv instead of argparse
- ❌ No usage/help documentation in scripts
- ❌ Scripts assume specific working directory
- ❌ Scripts not tested in CI environment
When NOT to Use
Do NOT use this skill when:
- Need complex orchestration (use workflow automation tools like Airflow)
- Building full CLI applications (use CLI frameworks like Click, Typer, Commander)
- Need daemon/service scripts (use systemd, supervisord)
- Implementing build pipelines (use dedicated build tools like Bazel, Gradle)
- Creating deployment automation (use Ansible, Terraform)
- Need GUI automation (use Selenium, Playwright)
- Scheduling tasks (use cron, systemd timers)
Use alternative skills:
workflow-orchestration- Complex multi-step workflowscli-application-patterns- Full-featured CLI appsbuild-automation- Comprehensive build systemsdeployment-automation- Infrastructure as code
Anti-Patterns (Avoid)
| Anti-Pattern | Problem | Solution |
|---|---|---|
| No error handling | Scripts fail silently | Use set -euo pipefail in bash |
| No cleanup | Temp files accumulate | Implement trap EXIT cleanup |
| Hardcoded paths | Not portable across systems | Use SCRIPT_DIR and relative paths |
| No help output | Users don't know how to use script | Add --help flag and usage function |
| Platform assumptions | Breaks on different OS | Detect OS/arch and adapt behavior |
| Using cd | Working directory confusion | Use absolute paths and cwd parameter |
| No logging | Hard to debug issues | Implement log_info and log_error |
| Ignoring exit codes | Failures cascade | Check $? or use && chaining |
Principles
This skill embodies these CODITECT principles:
- #3 Keep It Simple - Simple scripts for simple tasks
- #4 Self-Provisioning - Scripts detect and install dependencies
- #5 Eliminate Ambiguity - Clear error messages and logging
- #6 Clear, Understandable, Explainable - Help output documents usage
- #7 Inform, Don't Ask - Log progress, only prompt when necessary
- #8 No Assumptions - Detect platform and environment
- #9 Search Before Create - Reuse script templates and patterns
- #10 Complete Execution - Error handling ensures completion or clean failure
Full Principles: CODITECT-STANDARD-AUTOMATION.md