M

Master Linux Shell Scripting

All-in-one skill covering skill, should, used, user. Includes structured workflows, validation checks, and reusable patterns for development.

SkillClipticsdevelopmentv1.0.0MIT
0 views0 copies

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

FlagPurposePrevents
set -eExit on errorSilent failures continuing
set -uError on undefined variablesTypos causing empty strings
set -o pipefailPipe failure propagationHiding pipe command errors
IFS=$'\n\t'Safe word splittingSpace-separated filename issues
trap cleanup EXITGuaranteed cleanupResource 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

ParameterTypeDefaultDescription
shellstring"bash"Shell interpreter: bash, sh, zsh
strict_modebooleantrueEnable set -euo pipefail
loggingbooleantrueInclude logging functions
cleanup_trapbooleantrueAdd EXIT trap for cleanup
portabilitystring"bash"Portability: bash, posix, cross-platform
error_handlingstring"exit"Error behavior: exit, continue, retry

Best Practices

  1. 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.

  2. Quote all variable expansions — always use "$variable" not $variable; unquoted variables break on filenames with spaces and can cause glob expansion in unexpected ways.

  3. Use functions for reusable logic — declare functions with local variables to prevent pollution of the global namespace; functions make scripts testable and readable.

  4. Use mktemp for temporary files — never hardcode temp file paths like /tmp/myfile; mktemp creates unique files safely, preventing race conditions and security issues.

  5. 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.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates