bash-script-validator
npx skills add https://github.com/akin-ozer/cc-devops-skills --skill bash-script-validator
Agent 安装分布
Skill 文档
Bash Script Validator
Overview
This skill provides comprehensive validation for bash and shell scripts, checking for syntax errors, best practices, security vulnerabilities, and performance optimizations. It automatically detects whether a script is bash or POSIX sh based on the shebang and applies appropriate validation rules.
When to Use This Skill
Use this skill when:
- Validating bash or shell scripts (.sh, .bash files)
- Checking scripts for syntax errors before deployment
- Identifying bashisms in POSIX sh scripts
- Finding security vulnerabilities (unsafe eval, command injection)
- Optimizing script performance
- Ensuring POSIX compliance
- Debugging shell script issues
- Learning shell scripting best practices
- Code review of shell scripts
Validation Capabilities
1. Syntax Validation
- Bash scripts: Validates using
bash -n - POSIX sh scripts: Validates using
sh -n - Catches syntax errors before runtime
- Reports line numbers for syntax issues
2. ShellCheck Integration
- Comprehensive static analysis
- Hundreds of built-in checks
- Severity levels: error, warning, info, style
- Shell-specific validation (bash, sh, zsh, ksh)
- Links to detailed documentation for each issue
3. Security Checks
- Unsafe use of
evalwith variables - Command injection vulnerabilities
- Dangerous
rm -rfusage - Unquoted variables in dangerous contexts
- Missing input validation
4. Performance Optimizations
- Useless use of cat (UUOC)
- Inefficient loops
- Unnecessary subshells
- Multiple pipelines that could be combined
- Suggesting built-ins over external commands
5. Portability Checks (for sh scripts)
- Bashisms detection (arrays, [[ ]], etc.)
- Non-POSIX constructs
- Shell-specific features in sh scripts
- Recommends POSIX alternatives
6. Best Practices
- Missing error handling
- Unquoted variables
- Deprecated syntax (backticks)
- Proper use of
set -e,set -u,set -o pipefail - Function definition order
Quick Start
Basic Validation
# Validate a script
bash scripts/validate.sh path/to/script.sh
# The validator will:
# 1. Detect shell type from shebang
# 2. Run syntax validation
# 3. Run ShellCheck (if installed)
# 4. Run custom security/optimization checks
# 5. Generate detailed report
Example Output
========================================
BASH/SHELL SCRIPT VALIDATOR
========================================
File: myscript.sh
Detected Shell: bash
[SYNTAX CHECK]
â No syntax errors found (bash -n)
[SHELLCHECK]
myscript.sh:15:5: warning: Quote to prevent word splitting [SC2086]
myscript.sh:23:9: error: Use || exit to handle cd failure [SC2164]
[CUSTOM CHECKS]
â Potential command injection: eval with variable found
Line 42: eval $user_input
â¹ Useless use of cat detected
Line 18: cat file.txt | grep pattern
========================================
VALIDATION SUMMARY
========================================
Errors: 2
Warnings: 3
Info: 1
Usage in Claude Code
When validating shell scripts, Claude MUST follow these steps:
-
Invoke the validator on shell script files:
bash scripts/validate.sh <script-path> -
Analyze results to identify issues:
- Review errors, warnings, and info messages from the validator output
- Note ShellCheck error codes (SC####) for lookup
-
Reference documentation for detailed explanations:
- For ShellCheck codes: Read
docs/shellcheck-reference.md - For common mistakes: Read
docs/common-mistakes.md - For bash-specific issues: Read
docs/bash-reference.md - For POSIX sh issues: Read
docs/shell-reference.md
- For ShellCheck codes: Read
-
Suggest fixes with code examples:
- For each issue found, provide the corrected code
- Show before/after comparisons when helpful
- Reference the specific line numbers from the validation output
-
Explain best practices from the included guides:
- Explain WHY each fix improves the script
- Reference specific sections from the documentation files
Required Workflow
User: "Check this bash script for issues"
Claude MUST:
1. Run: bash scripts/validate.sh <script-path>
2. Read the validation output and identify all issues
3. Read docs/common-mistakes.md for fix patterns
4. Read docs/shellcheck-reference.md for SC error explanations (if needed)
5. For EACH issue found:
a. Show the problematic code
b. Explain the issue (referencing documentation)
c. Provide the corrected code
d. Explain why the fix improves the script
Example Response Format
After running the validator, Claude should respond with:
## Validation Results
Found X errors, Y warnings, Z info issues.
### Issue 1: Unquoted Variable (Line 25)
**Problem:**
\`\`\`bash
if [ ! -f $file ]; then # Word splitting risk
\`\`\`
**Reference:** See `common-mistakes.md` section "1. Unquoted Variables"
**Fix:**
\`\`\`bash
if [ ! -f "$file" ]; then # Properly quoted
\`\`\`
**Why:** Unquoted variables undergo word splitting and glob expansion,
causing unexpected behavior with filenames containing spaces or special characters.
### Issue 2: ...
Comprehensive Documentation
Core References
bash-reference.md
- Bash-specific features vs POSIX sh
- Parameter expansion
- Arrays and associative arrays
- Control structures
- Functions and scope
- Best practices
- Common pitfalls
shell-reference.md
- POSIX sh compliance
- Portable constructs
- Differences from bash
- Character classes
- POSIX utilities
- Testing for compliance
shellcheck-reference.md
- ShellCheck error codes explained
- Severity levels
- Configuration options
- Disabling checks
- CI/CD integration
- Editor integration
Tool References
grep-reference.md
- Basic and extended regex (BRE/ERE)
- Common grep patterns
- Performance tips
- Character classes
- Practical examples for scripts
awk-reference.md
- Field processing
- Built-in variables
- Pattern matching
- Arrays and functions
- Log analysis examples
- CSV/text processing
sed-reference.md
- Stream editing basics
- Substitution patterns
- Address ranges
- In-place editing
- Backreferences
- Common one-liners
regex-reference.md
- BRE vs ERE comparison
- POSIX character classes
- Metacharacters and escaping
- Backreferences
- Common patterns (IP, email, phone, etc.)
- Shell script regex examples
common-mistakes.md
- 25+ common shell scripting mistakes
- Real-world examples
- Consequences of each mistake
- Correct solutions
- Quick checklist
Example Scripts
Located in examples/ directory:
- good-bash.sh: Well-written bash script demonstrating best practices
- bad-bash.sh: Poorly-written bash script with common mistakes
- good-shell.sh: POSIX-compliant sh script
- bad-shell.sh: sh script with bashisms and errors
Use these for reference when learning or teaching shell scripting.
Validation Script Features
Automatic Shell Detection
The validator detects shell type from shebang:
#!/bin/bash,#!/usr/bin/env bashâ bash#!/bin/sh,#!/usr/bin/shâ POSIX sh#!/bin/zshâ zsh#!/bin/kshâ ksh#!/bin/dashâ dash
Multi-Layer Validation
- Syntax Check: Fast basic validation
- ShellCheck: Comprehensive static analysis (if installed)
- Custom Checks: Security and optimization patterns
- Report Generation: Color-coded, detailed output
Exit Codes
- 0: No issues found
- 1: Warnings found
- 2: Errors found
Installation Requirements
Required
- bash or sh (for running scripts)
ShellCheck Installation Options
The validator automatically detects and uses the best available ShellCheck installation:
Option 1: System-wide (Recommended – fastest)
# macOS
brew install shellcheck
# Ubuntu/Debian
apt-get install shellcheck
# Fedora
dnf install shellcheck
Option 2: Automatic via Wrapper (Python required)
# The wrapper automatically installs shellcheck-py in a venv
# Requires: python3 and pip3
./scripts/shellcheck_wrapper.sh --cache script.sh
# Cache location: ~/.cache/bash-script-validator/shellcheck-venv
# Clear cache: ./scripts/shellcheck_wrapper.sh --clear-cache
Option 3: Manual Python install
pip3 install shellcheck-py
The validator works without ShellCheck but provides enhanced validation when it’s available. The wrapper provides automatic installation with caching for faster subsequent runs.
Common Validation Scenarios
Scenario 1: Converting Bash Script to POSIX sh
# 1. Validate current bash script
bash scripts/validate.sh myscript.sh
# 2. Change shebang to #!/bin/sh
# 3. Re-validate - catches bashisms
bash scripts/validate.sh myscript.sh
# 4. Reference shell-reference.md for POSIX alternatives
# 5. Fix bashisms (arrays â set --, [[ ]] â [ ], etc.)
# 6. Re-validate until clean
Scenario 2: Security Audit
The validator automatically checks for:
- Unsafe
evalusage - Command injection risks
- Dangerous
rm -rfpatterns - Unquoted variables in dangerous contexts
Reference common-mistakes.md for detailed explanations.
Scenario 3: Performance Optimization
Identifies:
- Useless use of cat (UUOC)
- Inefficient file reading loops
- Unnecessary external commands
- Pipeline inefficiencies
Reference tool-specific docs (grep, awk, sed) for better patterns.
Integration with Development Workflow
Pre-commit Hook
#!/bin/bash
for file in $(git diff --cached --name-only --diff-filter=ACM | grep '\.sh$'); do
if ! bash .claude/skills/bash-script-validator/scripts/validate.sh "$file"; then
echo "Validation failed for $file"
exit 1
fi
done
CI/CD Integration
# Example for GitHub Actions
- name: Validate Shell Scripts
run: |
find . -name "*.sh" -exec bash .claude/skills/bash-script-validator/scripts/validate.sh {} \;
Learning Resources
Use the included documentation to:
- Learn bash scripting: Start with
bash-reference.md - Write portable scripts: Read
shell-reference.md - Master text processing: Study
grep,awk, andsedreferences - Understand regex: Reference
regex-reference.md - Avoid mistakes: Review
common-mistakes.md - Fix issues: Look up error codes in
shellcheck-reference.md
Best Practices
For Script Authors
- Always include a shebang
- Use
set -euo pipefailfor strict mode - Quote all variable expansions
- Check return codes for critical commands
- Use meaningful variable names
- Add comments for complex logic
- Validate scripts before committing
For Reviewers
- Run the validator on all scripts
- Check for security issues first
- Verify POSIX compliance if required
- Look for performance optimizations
- Ensure proper error handling
- Validate documentation/comments
Technical Details
Directory Structure
bash-script-validator/
âââ SKILL.md # This file
âââ scripts/
â âââ validate.sh # Main validation script
âââ docs/
â âââ bash-reference.md # Bash features and syntax
â âââ shell-reference.md # POSIX sh reference
â âââ shellcheck-reference.md # ShellCheck error codes
â âââ grep-reference.md # grep patterns and usage
â âââ awk-reference.md # AWK text processing
â âââ sed-reference.md # sed stream editing
â âââ regex-reference.md # Regular expressions
â âââ common-mistakes.md # Common pitfalls
âââ examples/
âââ good-bash.sh # Best practices example
âââ bad-bash.sh # Anti-patterns example
âââ good-shell.sh # POSIX sh example
âââ bad-shell.sh # Bashisms example
Validation Logic
The validator performs checks in this order:
- File existence and readability check
- Shebang detection â determines shell type
- Syntax validation â shell-specific (
bash -norsh -n) - ShellCheck validation â if installed, with appropriate shell dialect
- Custom security checks â pattern matching for vulnerabilities
- Custom portability checks â bashisms in sh scripts
- Summary generation â color-coded report with counts
Resources
Official Documentation
Internal References
All documentation is included in the docs/ directory for offline reference and context loading.
Note: This skill automatically loads relevant documentation based on the validation results, providing Claude with the necessary context to explain issues and suggest fixes effectively.