Complete bash-script toolkit with generation and validation capabilities
97
97%
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Risky
Do not use without reviewing
This skill generates production-ready bash scripts with best practices built-in: strict mode, error handling, logging, argument parsing, input validation, and cleanup traps. Use for system administration, text processing, API clients, automation workflows, and scheduled tasks.
Before writing any script, complete these steps:
Clarify ambiguities — ask if any of the following are unclear:
Explain your approach — before writing code, briefly describe:
references/text-processing-guide.mdUse the template for standard scripts (CLI tools, automation scripts):
bash scripts/generate_script_template.sh standard output-script.shThen customize for your specific use case.
Determine: purpose, input/output sources, bash vs POSIX sh, argument needs, error handling strategy, performance constraints, security requirements. Use AskUserQuestion for anything unclear.
set -euo pipefail, error functions, and trap cleanup#!/usr/bin/env bash
#
# Script Name: script-name.sh
# Description: Brief description
# Created: YYYY-MM-DD
#
set -euo pipefail
IFS=$'\n\t'
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")"
cleanup() {
local exit_code=$?
# Remove temp files, release locks, etc.
exit "${exit_code}"
}
trap cleanup EXIT ERR INT TERMFull implementations are in assets/templates/standard-template.sh. Key signatures to include:
Logging (one line per level):
log_info() { echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') - $*" >&2; }
log_warn() { echo "[WARN] $(date '+%Y-%m-%d %H:%M:%S') - $*" >&2; }
log_error() { echo "[ERROR] $(date '+%Y-%m-%d %H:%M:%S') - $*" >&2; }
log_fatal() { echo "[FATAL] $(date '+%Y-%m-%d %H:%M:%S') - $*" >&2; exit 1; }
# Add log_debug with LOG_LEVEL guard from template when DEBUG support is neededError handling:
die() { log_error "$@"; exit 1; }
check_command() { command -v "$1" &>/dev/null || die "Required command '$1' not found."; }
validate_file() { [[ -f "$1" ]] || die "File not found: $1"; [[ -r "$1" ]] || die "File not readable: $1"; }Argument parsing (getopts):
usage() {
cat << EOF
Usage: ${SCRIPT_NAME} [OPTIONS] [ARGUMENTS]
Options:
-h Show this help and exit
-v Enable verbose output
-f FILE Input file path
-o FILE Output file path
-d Enable debug logging
Examples:
${SCRIPT_NAME} -f input.txt -o output.txt
EOF
}
parse_args() {
while getopts ":hvf:o:d" opt; do
case ${opt} in
h) usage; exit 0 ;;
v) VERBOSE=true ;;
f) INPUT_FILE="${OPTARG}" ;;
o) OUTPUT_FILE="${OPTARG}" ;;
d) LOG_LEVEL="DEBUG" ;;
\?) echo "Invalid option: -${OPTARG}" >&2; usage; exit 1 ;;
:) echo "Option -${OPTARG} requires an argument" >&2; usage; exit 1 ;;
esac
done
shift $((OPTIND - 1))
}references/text-processing-guide.md for grep/awk/sed selectionmain() {
parse_args "$@" # From Stage 4
check_command "grep"
check_command "awk"
[[ -n "${INPUT_FILE:-}" ]] || die "Input file not specified. Use -f option."
validate_file "${INPUT_FILE}"
log_info "Starting processing..." # From Stage 4
# Main logic here
log_info "Processing completed successfully"
}
main "$@"#######################################
# Brief description of function
# Globals:
# VARIABLE_NAME
# Arguments:
# $1 - Description
# Outputs:
# Writes results to stdout
# Returns:
# 0 if successful, non-zero on error
#######################################After generating any script, invoke devops-skills:bash-script-validator:
Security:
"${var}" not $var[[ "${val}" =~ ^[a-zA-Z0-9/_.-]+$ ]] || die "Invalid"eval user input; use case statements insteadPerformance:
cat: grep pattern file not cat file | grep patternawk '/ERROR/{e++} /WARN/{w++} END{print e,w}' logMaintainability:
readonly for constantsPortability (POSIX sh):
[[ ]], $BASH_SOURCE; test with sh -n script.shSee references/script-patterns.md for full templates including text processing and parallel batch processing. Quick reference for simple CLI tools:
Pattern 1 – Simple CLI tool:
#!/usr/bin/env bash
set -euo pipefail
# For production scripts, use the full logging and argument parsing
# functions from Stage 4 above. This minimal example demonstrates structure:
usage() { cat << EOF
Usage: ${0##*/} [OPTIONS] FILE
-h Show help
-v Verbose
-o Output file
EOF
}
main() {
local verbose=false output_file="" input_file=""
while getopts ":hvo:" opt; do
case ${opt} in
h) usage; exit 0 ;; v) verbose=true ;; o) output_file="${OPTARG}" ;;
*) echo "Invalid option: -${OPTARG}" >&2; usage; exit 1 ;;
esac
done
shift $((OPTIND - 1))
input_file="${1:-}"
[[ -n "${input_file}" ]] || { echo "Error: FILE required" >&2; usage; exit 1; }
[[ -f "${input_file}" ]] || { echo "Error: File not found: ${input_file}" >&2; exit 1; }
if [[ -n "${output_file}" ]]; then
process_file "${input_file}" > "${output_file}"
else
process_file "${input_file}"
fi
}
process_file() { local file="$1"; cat "${file}"; }
main "$@"For text processing (grep/awk/sed pipelines) and parallel batch processing patterns, see references/script-patterns.md.
After every script, provide:
## Generated Script Summary
**File:** path/to/script.sh
**Architecture:** [main functions and purposes]
**Tool Selection:**
- grep: [why used]
- awk: [why used]
- sed: [why used / not needed]
**Key Features:** [list]
**Customization Points:** [variables/functions to modify]
**Usage:**
./script.sh --help
./script.sh -v input.log
**Validation Status:** ✅ Passed ShellCheck / ❌ Issues found (fixing...)
**Documentation References:**
- references/text-processing-guide.md (tool selection)
- references/script-patterns.md (argument parsing)set -euo pipefail-e causes exit on error, -u errors on unset variables, -o pipefail catches pipeline failures.#!/usr/bin/env bash with no error flags and silent failures.#!/usr/bin/env bash followed immediately by set -euo pipefail as the first two lines of every script.$VAR cause subtle bugs when values contain spaces or special characters.cp $SOURCE $DESTcp "$SOURCE" "$DEST"ls | grep to filter filesls output is not reliably parseable; it is locale-dependent and breaks on filenames with special characters.ls *.log | grep errorfor f in *.log; do grep error "$f"; done or find . -name "*.log" -exec grep error {} +python, node, or bash#!/usr/bin/python3 or /usr/local/bin/node script.js#!/usr/bin/env python3, rely on PATH for node script.js, or guard with command -v python3 || { echo "python3 required"; exit 1; }.eval to execute dynamically constructed commandseval enables code injection when any part of the command comes from user input or external data.eval "rm -rf $USER_INPUT"cmd=(rm -rf "$USER_INPUT"); "${cmd[@]}"Internal references (offline, load as context):
references/bash-scripting-guide.md — strict mode, functions, arrays, parameter expansionreferences/script-patterns.md — argument parsing, logging, retry logic, lock files, parallel processingreferences/text-processing-guide.md — grep/awk/sed selection, pipelines, large-file optimizationreferences/generation-best-practices.md — naming, documentation, testing, security, portabilityassets/templates/standard-template.sh — production-ready template with all componentsexamples/log-analyzer.sh — grep/awk/sed usage demonstrationscripts/generate_script_template.sh — template generator toolOfficial documentation:
All generated scripts are automatically validated using devops-skills:bash-script-validator to ensure correct syntax, ShellCheck compliance, security, and performance.