Master Linux Shell Scripting
All-in-one skill covering skill, should, used, user. Includes structured workflows, validation checks, and reusable patterns for development.
Linux Shell Scripting Skill
A Claude Code skill for writing production-ready shell scripts — covering Bash scripting patterns, system administration automation, error handling, logging, security practices, and portable script design.
When to Use This Skill
Choose this skill when:
- Automating system administration tasks (backups, monitoring, deployments)
- Writing setup scripts for development environments
- Creating cron jobs and scheduled maintenance scripts
- Building CI/CD pipeline scripts
- Managing users, permissions, and system configurations
- Diagnosing system issues with shell commands
Consider alternatives when:
- You need complex data processing (use Python or Node.js)
- You need cross-platform compatibility (use a scripting language)
- You need interactive CLI applications (use a CLI framework)
Quick Start
# Template for production-ready scripts #!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' # Configuration readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" readonly LOG_FILE="/var/log/$(basename "$0" .sh).log" # Logging function log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"; } err() { log "ERROR: $*" >&2; } # Cleanup on exit cleanup() { log "Script finished"; } trap cleanup EXIT # Main logic main() { log "Starting $(basename "$0")" # Your script logic here } main "$@"
Core Concepts
Script Safety Headers
| Flag | Purpose | Prevents |
|---|---|---|
set -e | Exit on error | Silent failures continuing |
set -u | Error on undefined variables | Typos causing empty strings |
set -o pipefail | Pipe failure propagation | Hiding pipe command errors |
IFS=$'\n\t' | Safe word splitting | Space-separated filename issues |
trap cleanup EXIT | Guaranteed cleanup | Resource leaks on failure |
Common Patterns
# Safe file operations tmpfile=$(mktemp) trap "rm -f '$tmpfile'" EXIT # Conditional execution with defaults DB_HOST="${DB_HOST:-localhost}" DB_PORT="${DB_PORT:-5432}" # Array iteration files=("file1.txt" "file2.txt" "file3.txt") for file in "${files[@]}"; do process "$file" done # Function with error handling backup_database() { local db_name="$1" local backup_dir="${2:-/backups}" local timestamp=$(date +%Y%m%d_%H%M%S) local backup_file="${backup_dir}/${db_name}_${timestamp}.sql.gz" pg_dump "$db_name" | gzip > "$backup_file" || { err "Failed to backup database: $db_name" return 1 } log "Backup created: $backup_file ($(du -h "$backup_file" | cut -f1))" } # Process monitoring check_service() { local service="$1" if systemctl is-active --quiet "$service"; then log "$service is running" else err "$service is not running — restarting" systemctl restart "$service" fi }
Configuration
| Parameter | Type | Default | Description |
|---|---|---|---|
shell | string | "bash" | Shell interpreter: bash, sh, zsh |
strict_mode | boolean | true | Enable set -euo pipefail |
logging | boolean | true | Include logging functions |
cleanup_trap | boolean | true | Add EXIT trap for cleanup |
portability | string | "bash" | Portability: bash, posix, cross-platform |
error_handling | string | "exit" | Error behavior: exit, continue, retry |
Best Practices
-
Always use
set -euo pipefail— these flags catch the vast majority of shell scripting bugs; without them, errors are silently ignored and undefined variables expand to empty strings. -
Quote all variable expansions — always use
"$variable"not$variable; unquoted variables break on filenames with spaces and can cause glob expansion in unexpected ways. -
Use functions for reusable logic — declare functions with
localvariables to prevent pollution of the global namespace; functions make scripts testable and readable. -
Use
mktempfor temporary files — never hardcode temp file paths like/tmp/myfile;mktempcreates unique files safely, preventing race conditions and security issues. -
Log to both stdout and a file — use
tee -a "$LOG_FILE"so output is visible during interactive runs and preserved for later debugging of automated runs.
Common Issues
Script breaks on filenames with spaces — Always quote variables and use "$@" instead of $*. Set IFS=$'\n\t' to prevent space-based word splitting in loops.
Script works interactively but fails in cron — Cron runs with a minimal PATH and no shell profile. Set PATH explicitly at the top of the script and use full paths for commands.
set -e doesn't catch errors in subshells — Errors in $(command) or command | other don't trigger set -e as expected. Use set -o pipefail for pipes and check $? explicitly for critical subshell commands.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Full-Stack Code Reviewer
Comprehensive code review skill that checks for security vulnerabilities, performance issues, accessibility, and best practices across frontend and backend code.
Test Suite Generator
Generates comprehensive test suites with unit tests, integration tests, and edge cases. Supports Jest, Vitest, Pytest, and Go testing.
Pro Architecture Workspace
Battle-tested skill for architectural, decision, making, framework. Includes structured workflows, validation checks, and reusable patterns for development.