shell

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Shell Scripts Best Practices

Shell脚本最佳实践

Comprehensive best practices guide for shell scripting, designed for AI agents and LLMs. Contains 48 rules across 9 categories, prioritized by impact from critical (safety, portability) to incremental (style). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics.
这是一份面向AI Agent和大语言模型的Shell脚本综合最佳实践指南。包含9个类别下的48条规则,按影响优先级排序,从关键(安全、可移植性)到增量(风格)依次排列。每条规则都配有详细说明、对比错误与正确实现的真实示例,以及具体的影响指标。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new bash or POSIX shell scripts
  • Reviewing shell scripts for security vulnerabilities
  • Debugging scripts that fail silently or behave unexpectedly
  • Porting scripts between Linux, macOS, and containers
  • Optimizing shell script performance
  • Setting up CI/CD pipelines with shell scripts
在以下场景中可参考本指南:
  • 编写新的bash或POSIX Shell脚本
  • 审查Shell脚本以排查安全漏洞
  • 调试静默失败或行为异常的脚本
  • 在Linux、macOS和容器之间移植脚本
  • 优化Shell脚本的性能
  • 使用Shell脚本搭建CI/CD流水线

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefixRules
1Safety & SecurityCRITICAL
safety-
6
2PortabilityCRITICAL
port-
5
3Error HandlingHIGH
err-
6
4Variables & DataHIGH
var-
5
5Quoting & ExpansionMEDIUM-HIGH
quote-
6
6Functions & StructureMEDIUM
func-
5
7Testing & ConditionalsMEDIUM
test-
5
8PerformanceLOW-MEDIUM
perf-
6
9Style & FormattingLOW
style-
4
优先级类别影响等级前缀规则数量
1安全与防护关键
safety-
6
2可移植性关键
port-
5
3错误处理
err-
6
4变量与数据
var-
5
5引用与展开中高
quote-
6
6函数与结构
func-
5
7测试与条件判断
test-
5
8性能中低
perf-
6
9风格与格式
style-
4

Quick Reference

快速参考

1. Safety & Security (CRITICAL)

1. 安全与防护(关键)

  • safety-command-injection
    - Prevent command injection from user input
  • safety-eval-avoidance
    - Avoid eval for dynamic commands
  • safety-absolute-paths
    - Use absolute paths for external commands
  • safety-temp-files
    - Create secure temporary files
  • safety-suid-forbidden
    - Never use SUID/SGID on shell scripts
  • safety-argument-injection
    - Prevent argument injection with double dash
  • safety-command-injection
    - 防止用户输入导致的命令注入
  • safety-eval-avoidance
    - 避免使用eval执行动态命令
  • safety-absolute-paths
    - 外部命令使用绝对路径
  • safety-temp-files
    - 创建安全的临时文件
  • safety-suid-forbidden
    - 绝不要在Shell脚本上使用SUID/SGID权限
  • safety-argument-injection
    - 使用双破折号防止参数注入

2. Portability (CRITICAL)

2. 可移植性(关键)

  • port-shebang-selection
    - Choose shebang based on portability needs
  • port-avoid-bashisms
    - Avoid bashisms in POSIX scripts
  • port-printf-over-echo
    - Use printf instead of echo for portability
  • port-export-syntax
    - Use portable export syntax
  • port-test-portability
    - Use portable test constructs
  • port-shebang-selection
    - 根据可移植性需求选择Shebang
  • port-avoid-bashisms
    - 在POSIX脚本中避免使用Bash特有语法
  • port-printf-over-echo
    - 为了可移植性使用printf而非echo
  • port-export-syntax
    - 使用可移植的export语法
  • port-test-portability
    - 使用可移植的测试结构

3. Error Handling (HIGH)

3. 错误处理(高)

  • err-strict-mode
    - Use strict mode for error detection
  • err-exit-codes
    - Use meaningful exit codes
  • err-trap-cleanup
    - Use trap for cleanup on exit
  • err-stderr-messages
    - Send error messages to stderr
  • err-pipefail
    - Use pipefail to catch pipeline errors
  • err-check-commands
    - Check command success explicitly
  • err-strict-mode
    - 使用严格模式检测错误
  • err-exit-codes
    - 使用有意义的退出码
  • err-trap-cleanup
    - 使用trap在退出时执行清理操作
  • err-stderr-messages
    - 将错误消息发送至stderr
  • err-pipefail
    - 使用pipefail捕获流水线错误
  • err-check-commands
    - 显式检查命令执行是否成功

4. Variables & Data (HIGH)

4. 变量与数据(高)

  • var-use-arrays
    - Use arrays for lists instead of strings
  • var-local-scope
    - Use local for function variables
  • var-naming-conventions
    - Follow variable naming conventions
  • var-readonly-constants
    - Use readonly for constants
  • var-default-values
    - Use parameter expansion for defaults
  • var-use-arrays
    - 使用数组而非字符串存储列表
  • var-local-scope
    - 函数变量使用local声明作用域
  • var-naming-conventions
    - 遵循变量命名规范
  • var-readonly-constants
    - 使用readonly声明常量
  • var-default-values
    - 使用参数展开设置默认值

5. Quoting & Expansion (MEDIUM-HIGH)

5. 引用与展开(中高)

  • quote-always-quote-variables
    - Always quote variable expansions
  • quote-dollar-at
    - Use "$@" for argument passing
  • quote-command-substitution
    - Quote command substitutions
  • quote-brace-expansion
    - Use braces for variable clarity
  • quote-here-documents
    - Use here documents for multi-line strings
  • quote-glob-safety
    - Control glob expansion explicitly
  • quote-always-quote-variables
    - 始终对变量展开进行引用
  • quote-dollar-at
    - 使用"$@"传递参数
  • quote-command-substitution
    - 对命令替换进行引用
  • quote-brace-expansion
    - 使用大括号提高变量可读性
  • quote-here-documents
    - 使用Here Document处理多行字符串
  • quote-glob-safety
    - 显式控制通配符展开

6. Functions & Structure (MEDIUM)

6. 函数与结构(中)

  • func-main-pattern
    - Use main() function pattern
  • func-single-purpose
    - Write single-purpose functions
  • func-return-values
    - Use return values correctly
  • func-documentation
    - Document functions with header comments
  • func-avoid-aliases
    - Prefer functions over aliases
  • func-main-pattern
    - 使用main()函数模式
  • func-single-purpose
    - 编写单一职责的函数
  • func-return-values
    - 正确使用返回值
  • func-documentation
    - 使用头部注释为函数添加文档
  • func-avoid-aliases
    - 优先使用函数而非别名

7. Testing & Conditionals (MEDIUM)

7. 测试与条件判断(中)

  • test-double-brackets
    - Use [[ ]] for tests in bash
  • test-arithmetic
    - Use (( )) for arithmetic comparisons
  • test-explicit-empty
    - Use explicit empty/non-empty string tests
  • test-file-operators
    - Use correct file test operators
  • test-case-patterns
    - Use case for pattern matching
  • test-double-brackets
    - 在Bash中使用[[ ]]进行测试
  • test-arithmetic
    - 使用(( ))进行算术比较
  • test-explicit-empty
    - 使用显式的空/非空字符串测试
  • test-file-operators
    - 使用正确的文件测试操作符
  • test-case-patterns
    - 使用case进行模式匹配

8. Performance (LOW-MEDIUM)

8. 性能(中低)

  • perf-builtins-over-external
    - Use builtins over external commands
  • perf-avoid-subshells
    - Avoid unnecessary subshells
  • perf-process-substitution
    - Use process substitution for temp files
  • perf-read-files
    - Read files efficiently
  • perf-parameter-expansion
    - Use parameter expansion for string operations
  • perf-batch-operations
    - Batch operations instead of loops
  • perf-builtins-over-external
    - 优先使用内置命令而非外部命令
  • perf-avoid-subshells
    - 避免不必要的子Shell
  • perf-process-substitution
    - 使用进程替换替代临时文件
  • perf-read-files
    - 高效读取文件
  • perf-parameter-expansion
    - 使用参数展开进行字符串操作
  • perf-batch-operations
    - 批量操作而非循环处理

9. Style & Formatting (LOW)

9. 风格与格式(低)

  • style-indentation
    - Use consistent indentation
  • style-file-structure
    - Follow consistent file structure
  • style-comments
    - Write useful comments
  • style-shellcheck
    - Use ShellCheck for static analysis
  • style-indentation
    - 使用一致的缩进
  • style-file-structure
    - 遵循一致的文件结构
  • style-comments
    - 编写有用的注释
  • style-shellcheck
    - 使用ShellCheck进行静态代码分析

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
阅读单个参考文件以获取详细说明和代码示例:
  • Section definitions - 类别结构与影响等级说明
  • Rule template - 添加新规则的模板

Reference Files

参考文件

FileDescription
AGENTS.mdComplete compiled guide with all rules
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
AGENTS.md包含所有规则的完整编译指南
references/_sections.md类别定义与排序说明
assets/templates/_template.md新规则模板
metadata.json版本与参考信息

Key Sources

主要参考来源