bash-script-validator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bash Script Validator

Bash脚本验证工具

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.
该技能为bash和shell脚本提供全面的验证功能,检查语法错误、最佳实践、安全漏洞以及性能优化。它会根据脚本的shebang自动检测脚本是bash还是POSIX sh,并应用相应的验证规则。

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
在以下场景中使用该技能:
  • 验证bash或shell脚本(.sh、.bash文件)
  • 部署前检查脚本的语法错误
  • 识别POSIX sh脚本中的bash特有语法(bashisms)
  • 发现安全漏洞(不安全的eval使用、命令注入)
  • 优化脚本性能
  • 确保POSIX合规性
  • 调试shell脚本问题
  • 学习shell脚本最佳实践
  • 对shell脚本进行代码评审

Validation Capabilities

验证能力

1. Syntax Validation

1. 语法验证

  • Bash scripts: Validates using
    bash -n
  • POSIX sh scripts: Validates using
    sh -n
  • Catches syntax errors before runtime
  • Reports line numbers for syntax issues
  • Bash脚本:使用
    bash -n
    进行验证
  • POSIX sh脚本:使用
    sh -n
    进行验证
  • 在运行前捕获语法错误
  • 报告语法问题所在的行号

2. ShellCheck Integration

2. ShellCheck集成

  • 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
  • 全面的静态代码分析
  • 内置数百项检查规则
  • 严重程度分级:错误、警告、信息、风格
  • 针对特定shell的验证(bash、sh、zsh、ksh)
  • 提供每个问题的详细文档链接

3. Security Checks

3. 安全检查

  • Unsafe use of
    eval
    with variables
  • Command injection vulnerabilities
  • Dangerous
    rm -rf
    usage
  • Unquoted variables in dangerous contexts
  • Missing input validation
  • 结合变量的不安全
    eval
    使用
  • 命令注入漏洞
  • 危险的
    rm -rf
    用法
  • 在危险场景中使用未加引号的变量
  • 缺少输入验证

4. Performance Optimizations

4. 性能优化

  • Useless use of cat (UUOC)
  • Inefficient loops
  • Unnecessary subshells
  • Multiple pipelines that could be combined
  • Suggesting built-ins over external commands
  • 无用的cat命令使用(UUOC)
  • 低效循环
  • 不必要的子shell
  • 可合并的多管道操作
  • 建议使用内置命令替代外部命令

5. Portability Checks (for sh scripts)

5. 可移植性检查(针对sh脚本)

  • Bashisms detection (arrays, [[ ]], etc.)
  • Non-POSIX constructs
  • Shell-specific features in sh scripts
  • Recommends POSIX alternatives
  • 检测bash特有语法(数组、[[ ]]等)
  • 非POSIX语法结构
  • sh脚本中使用的特定shell功能
  • 推荐POSIX兼容的替代方案

6. Best Practices

6. 最佳实践

  • Missing error handling
  • Unquoted variables
  • Deprecated syntax (backticks)
  • Proper use of
    set -e
    ,
    set -u
    ,
    set -o pipefail
  • Function definition order
  • 缺少错误处理
  • 未加引号的变量
  • 已弃用的语法(反引号)
  • 正确使用
    set -e
    set -u
    set -o pipefail
  • 函数定义顺序

Quick Start

快速开始

Basic Validation

基础验证

bash
undefined
bash
undefined

Validate a script

验证脚本

bash scripts/validate.sh path/to/script.sh
bash scripts/validate.sh path/to/script.sh

The validator will:

验证工具将执行以下操作:

1. Detect shell type from shebang

1. 从shebang检测shell类型

2. Run syntax validation

2. 运行语法验证

3. Run ShellCheck (if installed)

3. 运行ShellCheck(若已安装)

4. Run custom security/optimization checks

4. 运行自定义安全/优化检查

5. Generate detailed report

5. 生成详细报告

undefined
undefined

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
========================================
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

在Claude Code中的使用方法

When validating shell scripts, Claude MUST follow these steps:
  1. Invoke the validator on shell script files:
    bash
    bash scripts/validate.sh <script-path>
  2. Analyze results to identify issues:
    • Review errors, warnings, and info messages from the validator output
    • Note ShellCheck error codes (SC####) for lookup
  3. 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
  4. 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
  5. Explain best practices from the included guides:
    • Explain WHY each fix improves the script
    • Reference specific sections from the documentation files
验证shell脚本时,Claude必须遵循以下步骤:
  1. 调用验证工具处理shell脚本文件:
    bash
    bash scripts/validate.sh <script-path>
  2. 分析结果以识别问题:
    • 查看验证工具输出中的错误、警告和信息提示
    • 记录ShellCheck错误代码(SC####)以便查阅
  3. 参考文档获取详细说明:
    • 关于ShellCheck代码:阅读
      docs/shellcheck-reference.md
    • 关于常见错误:阅读
      docs/common-mistakes.md
    • 关于bash特定问题:阅读
      docs/bash-reference.md
    • 关于POSIX sh问题:阅读
      docs/shell-reference.md
  4. 提供修复建议并附带代码示例:
    • 针对每个发现的问题,提供修正后的代码
    • 必要时展示修改前后的对比
    • 参考验证输出中对应的行号
  5. 解释最佳实践(参考附带指南):
    • 解释每项修复如何改进脚本
    • 参考文档中的具体章节

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
用户:"检查这个bash脚本是否存在问题"

Claude必须:
1. 运行:bash scripts/validate.sh <script-path>
2. 读取验证输出并识别所有问题
3. 阅读docs/common-mistakes.md获取修复模式
4. 若需要,阅读docs/shellcheck-reference.md获取SC错误的解释
5. 针对每个发现的问题:
   a. 展示有问题的代码
   b. 解释问题(参考文档)
   c. 提供修正后的代码
   d. 解释修复为何能改进脚本

Example Response Format

示例响应格式

After running the validator, Claude should respond with:
markdown
undefined
运行验证工具后,Claude应按以下格式响应:
markdown
undefined

Validation Results

验证结果

Found X errors, Y warnings, Z info issues.
共发现X个错误、Y个警告、Z个信息提示。

Issue 1: Unquoted Variable (Line 25)

问题1:未加引号的变量(第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.
问题代码: ```bash if [ ! -f $file ]; then # 存在单词拆分风险 ```
参考文档: 请查看
common-mistakes.md
中的「1. 未加引号的变量」章节
修复代码: ```bash if [ ! -f "$file" ]; then # 正确添加引号 ```
修复原因: 未加引号的变量会进行单词拆分和通配符扩展,当文件名包含空格或特殊字符时会导致意外行为。

Issue 2: ...

问题2:...

undefined
undefined

Comprehensive Documentation

全面文档

Core References

核心参考文档

bash-reference.md

bash-reference.md

  • Bash-specific features vs POSIX sh
  • Parameter expansion
  • Arrays and associative arrays
  • Control structures
  • Functions and scope
  • Best practices
  • Common pitfalls
  • Bash特有的功能与POSIX sh的对比
  • 参数扩展
  • 数组与关联数组
  • 控制结构
  • 函数与作用域
  • 最佳实践
  • 常见陷阱

shell-reference.md

shell-reference.md

  • POSIX sh compliance
  • Portable constructs
  • Differences from bash
  • Character classes
  • POSIX utilities
  • Testing for compliance
  • POSIX sh合规性
  • 可移植语法结构
  • 与bash的差异
  • 字符类
  • POSIX工具
  • 合规性测试

shellcheck-reference.md

shellcheck-reference.md

  • ShellCheck error codes explained
  • Severity levels
  • Configuration options
  • Disabling checks
  • CI/CD integration
  • Editor integration
  • ShellCheck错误代码解释
  • 严重程度分级
  • 配置选项
  • 禁用检查规则
  • CI/CD集成
  • 编辑器集成

Tool References

工具参考文档

grep-reference.md

grep-reference.md

  • Basic and extended regex (BRE/ERE)
  • Common grep patterns
  • Performance tips
  • Character classes
  • Practical examples for scripts
  • 基础与扩展正则表达式(BRE/ERE)
  • 常见grep模式
  • 性能技巧
  • 字符类
  • 脚本中的实用示例

awk-reference.md

awk-reference.md

  • Field processing
  • Built-in variables
  • Pattern matching
  • Arrays and functions
  • Log analysis examples
  • CSV/text processing
  • 字段处理
  • 内置变量
  • 模式匹配
  • 数组与函数
  • 日志分析示例
  • CSV/文本处理

sed-reference.md

sed-reference.md

  • Stream editing basics
  • Substitution patterns
  • Address ranges
  • In-place editing
  • Backreferences
  • Common one-liners
  • 流编辑基础
  • 替换模式
  • 地址范围
  • 原地编辑
  • 反向引用
  • 常用单行命令

regex-reference.md

regex-reference.md

  • BRE vs ERE comparison
  • POSIX character classes
  • Metacharacters and escaping
  • Backreferences
  • Common patterns (IP, email, phone, etc.)
  • Shell script regex examples
  • BRE与ERE的对比
  • POSIX字符类
  • 元字符与转义
  • 反向引用
  • 常见模式(IP、邮箱、电话等)
  • Shell脚本正则表达式示例

common-mistakes.md

common-mistakes.md

  • 25+ common shell scripting mistakes
  • Real-world examples
  • Consequences of each mistake
  • Correct solutions
  • Quick checklist
  • 25+种常见shell脚本错误
  • 真实场景示例
  • 每个错误的后果
  • 正确解决方案
  • 快速检查清单

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.
位于
examples/
目录下:
  • good-bash.sh:编写规范的bash脚本,展示最佳实践
  • bad-bash.sh:编写不佳的bash脚本,包含常见错误
  • good-shell.sh:符合POSIX标准的sh脚本
  • bad-shell.sh:包含bash特有语法和错误的sh脚本
学习或教授shell脚本时,可将这些脚本作为参考。

Validation Script Features

验证脚本特性

Automatic Shell Detection

自动Shell检测

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
验证工具会根据shebang检测shell类型:
  • #!/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

多层验证

  1. Syntax Check: Fast basic validation
  2. ShellCheck: Comprehensive static analysis (if installed)
  3. Custom Checks: Security and optimization patterns
  4. Report Generation: Color-coded, detailed output
  1. 语法检查:快速基础验证
  2. ShellCheck:全面静态代码分析(若已安装)
  3. 自定义检查:安全与优化模式检查
  4. 报告生成:带颜色标记的详细输出

Exit Codes

退出码

  • 0: No issues found
  • 1: Warnings found
  • 2: Errors found
  • 0:未发现任何问题
  • 1:发现警告
  • 2:发现错误

Installation Requirements

安装要求

Required

必备条件

  • bash or sh (for running scripts)
  • bash或sh(用于运行脚本)

ShellCheck Installation Options

ShellCheck安装选项

The validator automatically detects and uses the best available ShellCheck installation:
Option 1: System-wide (Recommended - fastest)
bash
undefined
验证工具会自动检测并使用可用的最佳ShellCheck安装版本:
选项1:系统级安装(推荐 - 速度最快)
bash
undefined

macOS

macOS

brew install shellcheck
brew install shellcheck

Ubuntu/Debian

Ubuntu/Debian

apt-get install shellcheck
apt-get install shellcheck

Fedora

Fedora

dnf install shellcheck

**Option 2: Automatic via Wrapper (Python required)**
```bash
dnf install shellcheck

**选项2:通过包装器自动安装(需要Python)**
```bash

The wrapper automatically installs shellcheck-py in a venv

该包装器会在虚拟环境中自动安装shellcheck-py

Requires: python3 and pip3

要求:python3和pip3

./scripts/shellcheck_wrapper.sh --cache script.sh
./scripts/shellcheck_wrapper.sh --cache script.sh

Cache location: ~/.cache/bash-script-validator/shellcheck-venv

缓存位置:~/.cache/bash-script-validator/shellcheck-venv

Clear cache: ./scripts/shellcheck_wrapper.sh --clear-cache

清除缓存:./scripts/shellcheck_wrapper.sh --clear-cache


**Option 3: Manual Python install**
```bash
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.

**选项3:手动Python安装**
```bash
pip3 install shellcheck-py
即使没有ShellCheck,验证工具也能正常工作,但安装后可提供更强大的验证功能。包装器支持自动安装并缓存,可加快后续运行速度。

Common Validation Scenarios

常见验证场景

Scenario 1: Converting Bash Script to POSIX sh

场景1:将Bash脚本转换为POSIX sh

bash
undefined
bash
undefined

1. Validate current bash script

1. 验证当前bash脚本

bash scripts/validate.sh myscript.sh
bash scripts/validate.sh myscript.sh

2. Change shebang to #!/bin/sh

2. 将shebang修改为#!/bin/sh

3. Re-validate - catches bashisms

3. 重新验证 - 检测bash特有语法

bash scripts/validate.sh myscript.sh
bash scripts/validate.sh myscript.sh

4. Reference shell-reference.md for POSIX alternatives

4. 参考shell-reference.md获取POSIX兼容的替代方案

5. Fix bashisms (arrays → set --, [[ ]] → [ ], etc.)

5. 修复bash特有语法(数组→set --,[[ ]]→[ ]等)

6. Re-validate until clean

6. 重新验证直到无问题

undefined
undefined

Scenario 2: Security Audit

场景2:安全审计

The validator automatically checks for:
  • Unsafe
    eval
    usage
  • Command injection risks
  • Dangerous
    rm -rf
    patterns
  • Unquoted variables in dangerous contexts
Reference
common-mistakes.md
for detailed explanations.
验证工具会自动检查以下内容:
  • 不安全的
    eval
    用法
  • 命令注入风险
  • 危险的
    rm -rf
    模式
  • 在危险场景中使用未加引号的变量
参考
common-mistakes.md
获取详细说明。

Scenario 3: Performance Optimization

场景3:性能优化

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.
识别以下问题:
  • 无用的cat命令使用(UUOC)
  • 低效的文件读取循环
  • 不必要的外部命令
  • 管道操作低效
参考工具特定文档(grep、awk、sed)获取更优实现方式。

Integration with Development Workflow

与开发工作流集成

Pre-commit Hook

提交前钩子(Pre-commit Hook)

bash
#!/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
bash
#!/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 "$file验证失败"
        exit 1
    fi
done

CI/CD Integration

CI/CD集成

yaml
undefined
yaml
undefined

Example for GitHub Actions

GitHub Actions示例

  • name: Validate Shell Scripts run: | find . -name "*.sh" -exec bash .claude/skills/bash-script-validator/scripts/validate.sh {} ;
undefined
  • name: 验证Shell脚本 run: | find . -name "*.sh" -exec bash .claude/skills/bash-script-validator/scripts/validate.sh {} ;
undefined

Learning Resources

学习资源

Use the included documentation to:
  1. Learn bash scripting: Start with
    bash-reference.md
  2. Write portable scripts: Read
    shell-reference.md
  3. Master text processing: Study
    grep
    ,
    awk
    , and
    sed
    references
  4. Understand regex: Reference
    regex-reference.md
  5. Avoid mistakes: Review
    common-mistakes.md
  6. Fix issues: Look up error codes in
    shellcheck-reference.md
使用附带的文档进行学习:
  1. 学习bash脚本:从
    bash-reference.md
    开始
  2. 编写可移植脚本:阅读
    shell-reference.md
  3. 掌握文本处理:学习grep、awk和sed参考文档
  4. 理解正则表达式:参考
    regex-reference.md
  5. 避免常见错误:查看
    common-mistakes.md
  6. 修复问题:在
    shellcheck-reference.md
    中查找错误代码

Best Practices

最佳实践

For Script Authors

针对脚本作者

  1. Always include a shebang
  2. Use
    set -euo pipefail
    for strict mode
  3. Quote all variable expansions
  4. Check return codes for critical commands
  5. Use meaningful variable names
  6. Add comments for complex logic
  7. Validate scripts before committing
  1. 始终添加shebang
  2. 使用
    set -euo pipefail
    启用严格模式
  3. 所有变量扩展都添加引号
  4. 检查关键命令的返回码
  5. 使用有意义的变量名
  6. 为复杂逻辑添加注释
  7. 提交前验证脚本

For Reviewers

针对评审人员

  1. Run the validator on all scripts
  2. Check for security issues first
  3. Verify POSIX compliance if required
  4. Look for performance optimizations
  5. Ensure proper error handling
  6. Validate documentation/comments
  1. 对所有脚本运行验证工具
  2. 优先检查安全问题
  3. 若有要求,验证POSIX合规性
  4. 寻找性能优化空间
  5. 确保具备完善的错误处理
  6. 验证文档/注释的正确性

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
bash-script-validator/
├── SKILL.md                    # 本文档
├── scripts/
│   └── validate.sh             # 主验证脚本
├── docs/
│   ├── bash-reference.md       # Bash特性与语法
│   ├── shell-reference.md      # POSIX sh参考
│   ├── shellcheck-reference.md # ShellCheck错误代码
│   ├── grep-reference.md       # grep模式与用法
│   ├── awk-reference.md        # AWK文本处理
│   ├── sed-reference.md        # sed流编辑
│   ├── regex-reference.md      # 正则表达式
│   └── common-mistakes.md      # 常见陷阱
└── examples/
    ├── good-bash.sh            # 最佳实践示例
    ├── bad-bash.sh             # 反模式示例
    ├── good-shell.sh           # POSIX sh示例
    └── bad-shell.sh            # Bashisms示例

Validation Logic

验证逻辑

The validator performs checks in this order:
  1. File existence and readability check
  2. Shebang detection → determines shell type
  3. Syntax validation → shell-specific (
    bash -n
    or
    sh -n
    )
  4. ShellCheck validation → if installed, with appropriate shell dialect
  5. Custom security checks → pattern matching for vulnerabilities
  6. Custom portability checks → bashisms in sh scripts
  7. Summary generation → color-coded report with counts
验证工具按以下顺序执行检查:
  1. 文件存在性与可读性检查
  2. Shebang检测 → 确定shell类型
  3. 语法验证 → 特定shell的验证(
    bash -n
    sh -n
  4. ShellCheck验证 → 若已安装,使用对应shell方言进行检查
  5. 自定义安全检查 → 漏洞模式匹配
  6. 自定义可移植性检查 → sh脚本中的bash特有语法检测
  7. 生成摘要 → 带颜色标记的报告及统计数据

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.
所有文档都包含在
docs/
目录中,支持离线查阅和上下文加载。

注意:该技能会根据验证结果自动加载相关文档,为Claude提供必要的上下文,以便有效解释问题并提出修复建议。