bash-scripting
Bash scripting workflow for creating production-ready shell scripts with defensive patterns, error handling, and testing.
About this skill
This skill provides an AI agent with a structured, multi-phase workflow to design and generate high-quality bash scripts. It guides the agent through applying best practices for creating reliable, maintainable, and secure shell scripts suitable for production environments. The workflow emphasizes defining clear requirements, implementing defensive patterns to prevent common issues, incorporating robust error handling mechanisms, and integrating testing strategies to ensure script correctness and stability. It's ideal for automating system tasks, deploying applications, or building resilient CI/CD pipelines.
Best use case
Automating repetitive system tasks, creating reliable system administration tools, building robust deployment and CI/CD scripts, or developing secure backup solutions.
Bash scripting workflow for creating production-ready shell scripts with defensive patterns, error handling, and testing.
A well-structured, production-ready bash script that adheres to defensive programming principles, includes comprehensive error handling, and is designed with testing in mind, potentially accompanied by test suggestions or examples.
Practical example
Example input
Generate a bash script to automate daily backups of the `/var/www` directory to an S3 bucket, including proper error handling, logging, and a check for available disk space before starting.
Example output
```bash
#!/bin/bash
# --- Configuration ---
BACKUP_SOURCE="/var/www"
S3_BUCKET="s3://my-backup-bucket/daily"
LOG_FILE="/var/log/backup_script.log"
MIN_DISK_SPACE_MB=1024 # 1GB
DATE=$(date +%Y%m%d%H%M%S)
BACKUP_FILE="www_backup_${DATE}.tar.gz"
TEMP_DIR="/tmp"
# --- Defensive Patterns & Error Handling ---
# Exit immediately if a command exits with a non-zero status.
set -e
# Treat unset variables as an error.
set -u
# The return value of a pipeline is the status of the last command to exit with a non-zero status, or zero if no command exited with a non-zero status.
set -o pipefail
# Function for logging messages
log() {
echo "$(date +'%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}
# Error handling function
error_exit() {
log "ERROR: $1" >&2
log "Backup script failed. Exiting." >&2
exit 1
}
# --- Pre-flight Checks ---
# Check if necessary commands exist
command -v tar >/dev/null || error_exit "tar command not found."
command -v aws >/dev/null || error_exit "aws CLI command not found. Please install and configure AWS CLI."
# Check source directory existence
[ -d "$BACKUP_SOURCE" ] || error_exit "Backup source directory '$BACKUP_SOURCE' does not exist."
# Check disk space
AVAILABLE_SPACE_MB=$(df -m "$TEMP_DIR" | awk 'NR==2 {print $4}')
if (( AVAILABLE_SPACE_MB < MIN_DISK_SPACE_MB )); then
error_exit "Insufficient disk space in '$TEMP_DIR'. Required: ${MIN_DISK_SPACE_MB}MB, Available: ${AVAILABLE_SPACE_MB}MB."
fi
log "Disk space check passed. Available: ${AVAILABLE_SPACE_MB}MB."
# --- Main Backup Logic ---
log "Starting backup of '$BACKUP_SOURCE'..."
cd "$BACKUP_SOURCE" || error_exit "Failed to change directory to '$BACKUP_SOURCE'."
tar -czf "${TEMP_DIR}/${BACKUP_FILE}" . || error_exit "Tar compression failed."
log "Backup file '${TEMP_DIR}/${BACKUP_FILE}' created successfully."
log "Uploading '${BACKUP_FILE}' to '$S3_BUCKET'..."
aws s3 cp "${TEMP_DIR}/${BACKUP_FILE}" "$S3_BUCKET" --recursive || error_exit "S3 upload failed."
log "Backup uploaded to S3 successfully."
# --- Cleanup ---
log "Cleaning up temporary backup file..."
rm -f "${TEMP_DIR}/${BACKUP_FILE}" || log "Warning: Failed to remove temporary backup file '${TEMP_DIR}/${BACKUP_FILE}'."
log "Backup script finished successfully."
exit 0
```When to use this skill
- When generating automation scripts that require high reliability and error tolerance.
- For developing critical system administration or dev-ops tools.
- When constructing deployment or CI/CD scripts where failure detection and graceful exits are crucial.
- For creating backup solutions that need to be robust and handle unexpected scenarios.
When not to use this skill
- For simple, one-off commands or interactive shell use cases that don't require formal scripting.
- When the task is not related to bash scripting (e.g., Python, Node.js scripts).
- If the primary goal is not to produce a production-ready script, and a quick, simple script is sufficient without extensive error handling or testing.
- When the agent's task is merely to execute an existing script, rather than create or refine one.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/bash-scripting/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How bash-scripting Compares
| Feature / Agent | bash-scripting | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
Bash scripting workflow for creating production-ready shell scripts with defensive patterns, error handling, and testing.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
AI Agents for Startups
Explore AI agent skills for startup validation, product research, growth experiments, documentation, and fast execution with small teams.
SKILL.md Source
# Bash Scripting Workflow
## Overview
Specialized workflow for creating robust, production-ready bash scripts with defensive programming patterns, comprehensive error handling, and automated testing.
## When to Use This Workflow
Use this workflow when:
- Creating automation scripts
- Writing system administration tools
- Building deployment scripts
- Developing backup solutions
- Creating CI/CD scripts
## Workflow Phases
### Phase 1: Script Design
#### Skills to Invoke
- `bash-pro` - Professional scripting
- `bash-defensive-patterns` - Defensive patterns
#### Actions
1. Define script purpose
2. Identify inputs/outputs
3. Plan error handling
4. Design logging strategy
5. Document requirements
#### Copy-Paste Prompts
```
Use @bash-pro to design production-ready bash script
```
### Phase 2: Script Structure
#### Skills to Invoke
- `bash-pro` - Script structure
- `bash-defensive-patterns` - Safety patterns
#### Actions
1. Add shebang and strict mode
2. Create usage function
3. Implement argument parsing
4. Set up logging
5. Add cleanup handlers
#### Copy-Paste Prompts
```
Use @bash-defensive-patterns to implement strict mode and error handling
```
### Phase 3: Core Implementation
#### Skills to Invoke
- `bash-linux` - Linux commands
- `linux-shell-scripting` - Shell scripting
#### Actions
1. Implement main functions
2. Add input validation
3. Create helper functions
4. Handle edge cases
5. Add progress indicators
#### Copy-Paste Prompts
```
Use @bash-linux to implement system commands
```
### Phase 4: Error Handling
#### Skills to Invoke
- `bash-defensive-patterns` - Error handling
- `error-handling-patterns` - Error patterns
#### Actions
1. Add trap handlers
2. Implement retry logic
3. Create error messages
4. Set up exit codes
5. Add rollback capability
#### Copy-Paste Prompts
```
Use @bash-defensive-patterns to add comprehensive error handling
```
### Phase 5: Logging
#### Skills to Invoke
- `bash-pro` - Logging patterns
#### Actions
1. Create logging function
2. Add log levels
3. Implement timestamps
4. Configure log rotation
5. Add debug mode
#### Copy-Paste Prompts
```
Use @bash-pro to implement structured logging
```
### Phase 6: Testing
#### Skills to Invoke
- `bats-testing-patterns` - Bats testing
- `shellcheck-configuration` - ShellCheck
#### Actions
1. Write Bats tests
2. Run ShellCheck
3. Test edge cases
4. Verify error handling
5. Test with different inputs
#### Copy-Paste Prompts
```
Use @bats-testing-patterns to write script tests
```
```
Use @shellcheck-configuration to lint bash script
```
### Phase 7: Documentation
#### Skills to Invoke
- `documentation-templates` - Documentation
#### Actions
1. Add script header
2. Document functions
3. Create usage examples
4. List dependencies
5. Add troubleshooting section
#### Copy-Paste Prompts
```
Use @documentation-templates to document bash script
```
## Script Template
```bash
#!/usr/bin/env bash
set -euo pipefail
readonly SCRIPT_NAME=$(basename "$0")
readonly SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"; }
error() { log "ERROR: $*" >&2; exit 1; }
usage() { cat <<EOF
Usage: $SCRIPT_NAME [OPTIONS]
Options:
-h, --help Show help
-v, --verbose Verbose output
EOF
}
main() {
log "Script started"
# Implementation
log "Script completed"
}
main "$@"
```
## Quality Gates
- [ ] ShellCheck passes
- [ ] Bats tests pass
- [ ] Error handling works
- [ ] Logging functional
- [ ] Documentation complete
## Related Workflow Bundles
- `os-scripting` - OS scripting
- `linux-troubleshooting` - Linux troubleshooting
- `cloud-devops` - DevOps automationRelated Skills
linux-shell-scripting
Provide production-ready shell script templates for common Linux system administration tasks including backups, monitoring, user management, log analysis, and automation. These scripts serve as building blocks for security operations and penetration testing environments.
bash-pro
Master of defensive Bash scripting for production automation, CI/CD pipelines, and system utilities. Expert in safe, portable, and testable shell scripts.
bash-linux
Bash/Linux terminal patterns. Critical commands, piping, error handling, scripting. Use when working on macOS or Linux systems.
nft-standards
Master ERC-721 and ERC-1155 NFT standards, metadata best practices, and advanced NFT features.
nextjs-app-router-patterns
Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development.
new-rails-project
Create a new Rails project
networkx
NetworkX is a Python package for creating, manipulating, and analyzing complex networks and graphs.
network-engineer
Expert network engineer specializing in modern cloud networking, security architectures, and performance optimization.
nestjs-expert
You are an expert in Nest.js with deep knowledge of enterprise-grade Node.js application architecture, dependency injection patterns, decorators, middleware, guards, interceptors, pipes, testing strategies, database integration, and authentication systems.
nerdzao-elite
Senior Elite Software Engineer (15+) and Senior Product Designer. Full workflow with planning, architecture, TDD, clean code, and pixel-perfect UX validation.
nerdzao-elite-gemini-high
Modo Elite Coder + UX Pixel-Perfect otimizado especificamente para Gemini 3.1 Pro High. Workflow completo com foco em qualidade máxima e eficiência de tokens.
native-data-fetching
Use when implementing or debugging ANY network request, API call, or data fetching. Covers fetch API, React Query, SWR, error handling, caching, offline support, and Expo Router data loaders (useLoaderData).