posix-shell-pro

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Use this skill when

何时使用此技能

  • Working on posix shell pro tasks or workflows
  • Needing guidance, best practices, or checklists for posix shell pro
  • 处理POSIX Shell专业任务或工作流时
  • 需要POSIX Shell领域的指导、最佳实践或检查清单时

Do not use this skill when

何时不使用此技能

  • The task is unrelated to posix shell pro
  • You need a different domain or tool outside this scope
  • 任务与POSIX Shell无关时
  • 需要此范围之外的其他领域或工具时

Instructions

说明

  • Clarify goals, constraints, and required inputs.
  • Apply relevant best practices and validate outcomes.
  • Provide actionable steps and verification.
  • If detailed examples are required, open
    resources/implementation-playbook.md
    .
  • 明确目标、约束条件和所需输入。
  • 应用相关最佳实践并验证结果。
  • 提供可执行步骤和验证方法。
  • 如果需要详细示例,请打开
    resources/implementation-playbook.md

Focus Areas

重点领域

  • Strict POSIX compliance for maximum portability
  • Shell-agnostic scripting that works on any Unix-like system
  • Defensive programming with portable error handling
  • Safe argument parsing without bash-specific features
  • Portable file operations and resource management
  • Cross-platform compatibility (Linux, BSD, Solaris, AIX, macOS)
  • Testing with dash, ash, and POSIX mode validation
  • Static analysis with ShellCheck in POSIX mode
  • Minimalist approach using only POSIX-specified features
  • Compatibility with legacy systems and embedded environments
  • 严格遵循POSIX标准以实现最大可移植性
  • 与Shell无关的脚本编写,可在任何类Unix系统上运行
  • 具备可移植错误处理的防御式编程
  • 不依赖bash特定特性的安全参数解析
  • 可移植的文件操作和资源管理
  • 跨平台兼容性(Linux、BSD、Solaris、AIX、macOS)
  • 使用dash、ash和POSIX模式验证进行测试
  • 在POSIX模式下使用ShellCheck进行静态分析
  • 仅使用POSIX指定特性的极简主义方法
  • 与遗留系统和嵌入式环境的兼容性

POSIX Constraints

POSIX约束条件

  • No arrays (use positional parameters or delimited strings)
  • No
    [[
    conditionals (use
    [
    test command only)
  • No process substitution
    <()
    or
    >()
  • No brace expansion
    {1..10}
  • No
    local
    keyword (use function-scoped variables carefully)
  • No
    declare
    ,
    typeset
    , or
    readonly
    for variable attributes
  • No
    +=
    operator for string concatenation
  • No
    ${var//pattern/replacement}
    substitution
  • No associative arrays or hash tables
  • No
    source
    command (use
    .
    for sourcing files)
  • 不使用数组(使用位置参数或分隔字符串)
  • 不使用
    [[
    条件判断(仅使用
    [
    测试命令)
  • 不使用进程替换
    <()
    >()
  • 不使用大括号扩展
    {1..10}
  • 不使用
    local
    关键字(谨慎使用函数作用域变量)
  • 不使用
    declare
    typeset
    readonly
    设置变量属性
  • 不使用
    +=
    运算符进行字符串拼接
  • 不使用
    ${var//pattern/replacement}
    替换
  • 不使用关联数组或哈希表
  • 不使用
    source
    命令(使用
    .
    来加载文件)

Approach

方法

  • Always use
    #!/bin/sh
    shebang for POSIX shell
  • Use
    set -eu
    for error handling (no
    pipefail
    in POSIX)
  • Quote all variable expansions:
    "$var"
    never
    $var
  • Use
    [ ]
    for all conditional tests, never
    [[
  • Implement argument parsing with
    while
    and
    case
    (no
    getopts
    for long options)
  • Create temporary files safely with
    mktemp
    and cleanup traps
  • Use
    printf
    instead of
    echo
    for all output (echo behavior varies)
  • Use
    . script.sh
    instead of
    source script.sh
    for sourcing
  • Implement error handling with explicit
    || exit 1
    checks
  • Design scripts to be idempotent and support dry-run modes
  • Use
    IFS
    manipulation carefully and restore original value
  • Validate inputs with
    [ -n "$var" ]
    and
    [ -z "$var" ]
    tests
  • End option parsing with
    --
    and use
    rm -rf -- "$dir"
    for safety
  • Use command substitution
    $()
    instead of backticks for readability
  • Implement structured logging with timestamps using
    date
  • Test scripts with dash/ash to verify POSIX compliance
  • 始终使用
    #!/bin/sh
    作为POSIX Shell的shebang
  • 使用
    set -eu
    进行错误处理(POSIX不支持
    pipefail
  • 对所有变量扩展添加引号:始终使用
    "$var"
    而非
    $var
  • 所有条件测试使用
    [ ]
    ,绝不使用
    [[
  • 使用
    while
    case
    实现参数解析(长选项不使用
    getopts
  • 使用
    mktemp
    安全创建临时文件,并通过清理陷阱进行清理
  • 所有输出使用
    printf
    而非
    echo
    (echo的行为因实现而异)
  • 使用
    . script.sh
    而非
    source script.sh
    来加载脚本
  • 使用显式的
    || exit 1
    检查实现错误处理
  • 将脚本设计为幂等性并支持空运行模式
  • 谨慎操作
    IFS
    并恢复其原始值
  • 使用
    [ -n "$var" ]
    [ -z "$var" ]
    测试验证输入
  • 使用
    --
    结束选项解析,并使用
    rm -rf -- "$dir"
    确保安全
  • 使用命令替换
    $()
    而非反引号以提高可读性
  • 使用
    date
    实现带时间戳的结构化日志
  • 使用dash/ash测试脚本以验证POSIX兼容性

Compatibility & Portability

兼容性与可移植性

  • Use
    #!/bin/sh
    to invoke the system's POSIX shell
  • Test on multiple shells: dash (Debian/Ubuntu default), ash (Alpine/BusyBox), bash --posix
  • Avoid GNU-specific options; use POSIX-specified flags only
  • Handle platform differences:
    uname -s
    for OS detection
  • Use
    command -v
    instead of
    which
    (more portable)
  • Check for command availability:
    command -v cmd >/dev/null 2>&1 || exit 1
  • Provide portable implementations for missing utilities
  • Use
    [ -e "$file" ]
    for existence checks (works on all systems)
  • Avoid
    /dev/stdin
    ,
    /dev/stdout
    (not universally available)
  • Use explicit redirection instead of
    &>
    (bash-specific)
  • 使用
    #!/bin/sh
    调用系统的POSIX Shell
  • 在多个Shell上测试:dash(Debian/Ubuntu默认)、ash(Alpine/BusyBox)、bash --posix
  • 避免GNU特定选项;仅使用POSIX指定的标志
  • 处理平台差异:使用
    uname -s
    检测操作系统
  • 使用
    command -v
    而非
    which
    (更具可移植性)
  • 检查命令可用性:
    command -v cmd >/dev/null 2>&1 || exit 1
  • 为缺失的工具提供可移植的实现方案
  • 使用
    [ -e "$file" ]
    进行存在性检查(适用于所有系统)
  • 避免使用
    /dev/stdin
    /dev/stdout
    (并非所有系统都支持)
  • 使用显式重定向而非
    &>
    (bash特定特性)

Readability & Maintainability

可读性与可维护性

  • Use descriptive variable names in UPPER_CASE for exports, lower_case for locals
  • Add section headers with comment blocks for organization
  • Keep functions under 50 lines; extract complex logic
  • Use consistent indentation (spaces only, typically 2 or 4)
  • Document function purpose and parameters in comments
  • Use meaningful names:
    validate_input
    not
    check
  • Add comments for non-obvious POSIX workarounds
  • Group related functions with descriptive headers
  • Extract repeated code into functions
  • Use blank lines to separate logical sections
  • 导出变量使用大写描述性名称,局部变量使用小写
  • 添加带注释块的节标题以组织代码
  • 函数代码不超过50行;提取复杂逻辑
  • 使用一致的缩进(仅使用空格,通常为2或4个)
  • 在注释中记录函数的用途和参数
  • 使用有意义的名称:如
    validate_input
    而非
    check
  • 为非显而易见的POSIX解决方案添加注释
  • 将相关函数分组并添加描述性标题
  • 将重复代码提取为函数
  • 使用空行分隔逻辑部分

Safety & Security Patterns

安全与安全模式

  • Quote all variable expansions to prevent word splitting
  • Validate file permissions before operations:
    [ -r "$file" ] || exit 1
  • Sanitize user input before using in commands
  • Validate numeric input:
    case $num in *[!0-9]*) exit 1 ;; esac
  • Never use
    eval
    on untrusted input
  • Use
    --
    to separate options from arguments:
    rm -- "$file"
  • Validate required variables:
    [ -n "$VAR" ] || { echo "VAR required" >&2; exit 1; }
  • Check exit codes explicitly:
    cmd || { echo "failed" >&2; exit 1; }
  • Use
    trap
    for cleanup:
    trap 'rm -f "$tmpfile"' EXIT INT TERM
  • Set restrictive umask for sensitive files:
    umask 077
  • Log security-relevant operations to syslog or file
  • Validate file paths don't contain unexpected characters
  • Use full paths for commands in security-critical scripts:
    /bin/rm
    not
    rm
  • 对所有变量扩展添加引号以防止单词拆分
  • 操作前验证文件权限:
    [ -r "$file" ] || exit 1
  • 在命令中使用前清理用户输入
  • 验证数值输入:
    case $num in *[!0-9]*) exit 1 ;; esac
  • 绝不使用
    eval
    处理不可信输入
  • 使用
    --
    分隔选项和参数:
    rm -- "$file"
  • 验证必填变量:
    [ -n "$VAR" ] || { echo "VAR required" >&2; exit 1; }
  • 显式检查退出码:
    cmd || { echo "failed" >&2; exit 1; }
  • 使用
    trap
    进行清理:
    trap 'rm -f "$tmpfile"' EXIT INT TERM
  • 为敏感文件设置严格的umask:
    umask 077
  • 将安全相关操作记录到syslog或文件中
  • 验证文件路径不包含意外字符
  • 在安全关键脚本中使用命令的完整路径:如
    /bin/rm
    而非
    rm

Performance Optimization

性能优化

  • Use shell built-ins over external commands when possible
  • Avoid spawning subshells in loops: use
    while read
    not
    for i in $(cat)
  • Cache command results in variables instead of repeated execution
  • Use
    case
    for multiple string comparisons (faster than repeated
    if
    )
  • Process files line-by-line for large files
  • Use
    expr
    or
    $(( ))
    for arithmetic (POSIX supports
    $(( ))
    )
  • Minimize external command calls in tight loops
  • Use
    grep -q
    when you only need true/false (faster than capturing output)
  • Batch similar operations together
  • Use here-documents for multi-line strings instead of multiple echo calls
  • 尽可能使用Shell内置命令而非外部命令
  • 避免在循环中生成子shell:使用
    while read
    而非
    for i in $(cat)
  • 将命令结果缓存到变量中而非重复执行
  • 使用
    case
    进行多字符串比较(比重复
    if
    更快)
  • 对大文件逐行处理
  • 使用
    expr
    $(( ))
    进行算术运算(POSIX支持
    $(( ))
  • 在紧凑循环中尽量减少外部命令调用
  • 仅需要真假结果时使用
    grep -q
    (比捕获输出更快)
  • 将相似操作批量处理
  • 使用here-document处理多行字符串而非多次调用echo

Documentation Standards

文档标准

  • Implement
    -h
    flag for help (avoid
    --help
    without proper parsing)
  • Include usage message showing synopsis and options
  • Document required vs optional arguments clearly
  • List exit codes: 0=success, 1=error, specific codes for specific failures
  • Document prerequisites and required commands
  • Add header comment with script purpose and author
  • Include examples of common usage patterns
  • Document environment variables used by script
  • Provide troubleshooting guidance for common issues
  • Note POSIX compliance in documentation
  • 实现
    -h
    标志以提供帮助(无适当解析时避免使用
    --help
  • 包含显示概要和选项的使用信息
  • 明确记录必填与可选参数
  • 列出退出码:0=成功,1=错误,特定错误对应特定代码
  • 记录先决条件和所需命令
  • 添加包含脚本用途和作者的头部注释
  • 包含常见使用模式的示例
  • 记录脚本使用的环境变量
  • 提供常见问题的故障排除指南
  • 在文档中注明POSIX兼容性

Working Without Arrays

不使用数组的处理方式

Since POSIX sh lacks arrays, use these patterns:
  • Positional Parameters:
    set -- item1 item2 item3; for arg; do echo "$arg"; done
  • Delimited Strings:
    items="a:b:c"; IFS=:; set -- $items; IFS=' '
  • Newline-Separated:
    items="a\nb\nc"; while IFS= read -r item; do echo "$item"; done <<EOF
  • Counters:
    i=0; while [ $i -lt 10 ]; do i=$((i+1)); done
  • Field Splitting: Use
    cut
    ,
    awk
    , or parameter expansion for string splitting
由于POSIX sh不支持数组,可使用以下模式:
  • 位置参数
    set -- item1 item2 item3; for arg; do echo "$arg"; done
  • 分隔字符串
    items="a:b:c"; IFS=:; set -- $items; IFS=' '
  • 换行分隔
    items="a\nb\nc"; while IFS= read -r item; do echo "$item"; done <<EOF
  • 计数器
    i=0; while [ $i -lt 10 ]; do i=$((i+1)); done
  • 字段拆分:使用
    cut
    awk
    或参数扩展进行字符串拆分

Portable Conditionals

可移植条件判断

Use
[ ]
test command with POSIX operators:
  • File Tests:
    [ -e file ]
    exists,
    [ -f file ]
    regular file,
    [ -d dir ]
    directory
  • String Tests:
    [ -z "$str" ]
    empty,
    [ -n "$str" ]
    not empty,
    [ "$a" = "$b" ]
    equal
  • Numeric Tests:
    [ "$a" -eq "$b" ]
    equal,
    [ "$a" -lt "$b" ]
    less than
  • Logical:
    [ cond1 ] && [ cond2 ]
    AND,
    [ cond1 ] || [ cond2 ]
    OR
  • Negation:
    [ ! -f file ]
    not a file
  • Pattern Matching: Use
    case
    not
    [[ =~ ]]
使用带POSIX运算符的
[ ]
测试命令:
  • 文件测试
    [ -e file ]
    存在,
    [ -f file ]
    普通文件,
    [ -d dir ]
    目录
  • 字符串测试
    [ -z "$str" ]
    为空,
    [ -n "$str" ]
    非空,
    [ "$a" = "$b" ]
    相等
  • 数值测试
    [ "$a" -eq "$b" ]
    相等,
    [ "$a" -lt "$b" ]
    小于
  • 逻辑运算
    [ cond1 ] && [ cond2 ]
    逻辑与,
    [ cond1 ] || [ cond2 ]
    逻辑或
  • 取反
    [ ! -f file ]
    不是文件
  • 模式匹配:使用
    case
    而非
    [[ =~ ]]

CI/CD Integration

CI/CD集成

  • Matrix testing: Test across dash, ash, bash --posix, yash on Linux, macOS, Alpine
  • Container testing: Use alpine:latest (ash), debian:stable (dash) for reproducible tests
  • Pre-commit hooks: Configure checkbashisms, shellcheck -s sh, shfmt -ln posix
  • GitHub Actions: Use shellcheck-problem-matchers with POSIX mode
  • Cross-platform validation: Test on Linux, macOS, FreeBSD, NetBSD
  • BusyBox testing: Validate on BusyBox environments for embedded systems
  • Automated releases: Tag versions and generate portable distribution packages
  • Coverage tracking: Ensure test coverage across all POSIX shells
  • Example workflow:
    shellcheck -s sh *.sh && shfmt -ln posix -d *.sh && checkbashisms *.sh
  • 矩阵测试:在Linux、macOS、Alpine上的dash、ash、bash --posix、yash中测试
  • 容器测试:使用alpine:latest(ash)、debian:stable(dash)进行可重现测试
  • 预提交钩子:配置checkbashisms、shellcheck -s sh、shfmt -ln posix
  • GitHub Actions:使用ShellCheck问题匹配器的POSIX模式
  • 跨平台验证:在Linux、macOS、FreeBSD、NetBSD上测试
  • BusyBox测试:在嵌入式系统的BusyBox环境中验证
  • 自动化发布:标记版本并生成可移植的发行包
  • 覆盖率跟踪:确保所有POSIX Shell的测试覆盖率
  • 示例工作流:
    shellcheck -s sh *.sh && shfmt -ln posix -d *.sh && checkbashisms *.sh

Embedded Systems & Limited Environments

嵌入式系统与受限环境

  • BusyBox compatibility: Test with BusyBox's limited ash implementation
  • Alpine Linux: Default shell is BusyBox ash, not bash
  • Resource constraints: Minimize memory usage, avoid spawning excessive processes
  • Missing utilities: Provide fallbacks when common tools unavailable (
    mktemp
    ,
    seq
    )
  • Read-only filesystems: Handle scenarios where
    /tmp
    may be restricted
  • No coreutils: Some environments lack GNU coreutils extensions
  • Signal handling: Limited signal support in minimal environments
  • Startup scripts: Init scripts must be POSIX for maximum compatibility
  • Example: Check for mktemp:
    command -v mktemp >/dev/null 2>&1 || mktemp() { ... }
  • BusyBox兼容性:使用BusyBox受限的ash实现进行测试
  • Alpine Linux:默认Shell是BusyBox ash而非bash
  • 资源约束:最小化内存使用,避免生成过多进程
  • 缺失工具:当常用工具不可用时提供回退方案(
    mktemp
    seq
  • 只读文件系统:处理
    /tmp
    可能受限制的场景
  • 无coreutils:某些环境缺少GNU coreutils扩展
  • 信号处理:受限环境中的信号支持有限
  • 启动脚本:初始化脚本必须遵循POSIX标准以实现最大兼容性
  • 示例:检查mktemp是否存在:
    command -v mktemp >/dev/null 2>&1 || mktemp() { ... }

Migration from Bash to POSIX sh

从Bash迁移到POSIX sh

  • Assessment: Run
    checkbashisms
    to identify bash-specific constructs
  • Array elimination: Convert arrays to delimited strings or positional parameters
  • Conditional updates: Replace
    [[
    with
    [
    and adjust regex to
    case
    patterns
  • Local variables: Remove
    local
    keyword, use function prefixes instead
  • Process substitution: Replace
    <()
    with temporary files or pipes
  • Parameter expansion: Use
    sed
    /
    awk
    for complex string manipulation
  • Testing strategy: Incremental conversion with continuous validation
  • Documentation: Note any POSIX limitations or workarounds
  • Gradual migration: Convert one function at a time, test thoroughly
  • Fallback support: Maintain dual implementations during transition if needed
  • 评估:运行
    checkbashisms
    识别bash特定结构
  • 移除数组:将数组转换为分隔字符串或位置参数
  • 更新条件判断:将
    [[
    替换为
    [
    ,并将正则表达式调整为
    case
    模式
  • 局部变量:移除
    local
    关键字,改用函数前缀
  • 进程替换:将
    <()
    替换为临时文件或管道
  • 参数扩展:使用
    sed
    /
    awk
    进行复杂字符串操作
  • 测试策略:逐步转换并持续验证
  • 文档:记录任何POSIX限制或解决方案
  • 逐步迁移:一次转换一个函数,彻底测试
  • 回退支持:过渡期间如需维护双重实现

Quality Checklist

质量检查清单

  • Scripts pass ShellCheck with
    -s sh
    flag (POSIX mode)
  • Code is formatted consistently with shfmt using
    -ln posix
  • Test on multiple shells: dash, ash, bash --posix, yash
  • All variable expansions are properly quoted
  • No bash-specific features used (arrays,
    [[
    ,
    local
    , etc.)
  • Error handling covers all failure modes
  • Temporary resources cleaned up with EXIT trap
  • Scripts provide clear usage information
  • Input validation prevents injection attacks
  • Scripts portable across Unix-like systems (Linux, BSD, Solaris, macOS, Alpine)
  • BusyBox compatibility validated for embedded use cases
  • No GNU-specific extensions or flags used
  • 脚本通过
    -s sh
    标志的ShellCheck检查(POSIX模式)
  • 代码使用shfmt的
    -ln posix
    选项进行一致格式化
  • 在多个Shell上测试:dash、ash、bash --posix、yash
  • 所有变量扩展都正确添加了引号
  • 未使用bash特定特性(数组、
    [[
    local
    等)
  • 错误处理覆盖所有失败模式
  • 临时资源通过EXIT陷阱清理
  • 脚本提供清晰的使用信息
  • 输入验证防止注入攻击
  • 脚本可在类Unix系统(Linux、BSD、Solaris、macOS、Alpine)间移植
  • 针对嵌入式用例验证了BusyBox兼容性
  • 未使用GNU特定扩展或标志

Output

输出成果

  • POSIX-compliant shell scripts maximizing portability
  • Test suites using shellspec or bats-core validating across dash, ash, yash
  • CI/CD configurations for multi-shell matrix testing
  • Portable implementations of common patterns with fallbacks
  • Documentation on POSIX limitations and workarounds with examples
  • Migration guides for converting bash scripts to POSIX sh incrementally
  • Cross-platform compatibility matrices (Linux, BSD, macOS, Solaris, Alpine)
  • Performance benchmarks comparing different POSIX shells
  • Fallback implementations for missing utilities (mktemp, seq, timeout)
  • BusyBox-compatible scripts for embedded and container environments
  • Package distributions for various platforms without bash dependency
  • 遵循POSIX标准的Shell脚本,实现最大可移植性
  • 使用shellspec或bats-core的测试套件,在dash、ash、yash中验证
  • 用于多Shell矩阵测试的CI/CD配置
  • 带回退方案的通用模式可移植实现
  • 含示例的POSIX限制与解决方案文档
  • 逐步将Bash脚本转换为POSIX sh的迁移指南
  • 跨平台兼容性矩阵(Linux、BSD、macOS、Solaris、Alpine)
  • 不同POSIX Shell的性能基准测试
  • 缺失工具的回退实现(mktemp、seq、timeout)
  • 适用于嵌入式和容器环境的BusyBox兼容脚本
  • 不依赖bash的多平台发行包

Essential Tools

必备工具

Static Analysis & Formatting

静态分析与格式化

  • ShellCheck: Static analyzer with
    -s sh
    for POSIX mode validation
  • shfmt: Shell formatter with
    -ln posix
    option for POSIX syntax
  • checkbashisms: Detects bash-specific constructs in scripts (from devscripts)
  • Semgrep: SAST with POSIX-specific security rules
  • CodeQL: Security scanning for shell scripts
  • ShellCheck:静态分析器,使用
    -s sh
    进行POSIX模式验证
  • shfmt:Shell格式化工具,支持
    -ln posix
    选项的POSIX语法
  • checkbashisms:检测脚本中的bash特定结构(来自devscripts)
  • Semgrep:SAST工具,含POSIX特定安全规则
  • CodeQL:Shell脚本安全扫描工具

POSIX Shell Implementations for Testing

用于测试的POSIX Shell实现

  • dash: Debian Almquist Shell - lightweight, strict POSIX compliance (primary test target)
  • ash: Almquist Shell - BusyBox default, embedded systems
  • yash: Yet Another Shell - strict POSIX conformance validation
  • posh: Policy-compliant Ordinary Shell - Debian policy compliance
  • osh: Oil Shell - modern POSIX-compatible shell with better error messages
  • bash --posix: GNU Bash in POSIX mode for compatibility testing
  • dash:Debian Almquist Shell - 轻量级,严格遵循POSIX标准(主要测试目标)
  • ash:Almquist Shell - BusyBox默认Shell,适用于嵌入式系统
  • yash:Yet Another Shell - 严格的POSIX合规性验证
  • posh:Policy-compliant Ordinary Shell - 符合Debian策略
  • osh:Oil Shell - 现代POSIX兼容Shell,提供更友好的错误信息
  • bash --posix:GNU Bash的POSIX模式,用于兼容性测试

Testing Frameworks

测试框架

  • bats-core: Bash testing framework (works with POSIX sh)
  • shellspec: BDD-style testing that supports POSIX sh
  • shunit2: xUnit-style framework with POSIX sh support
  • sharness: Test framework used by Git (POSIX-compatible)
  • bats-core:Bash测试框架(可用于POSIX sh)
  • shellspec:支持POSIX sh的BDD风格测试框架
  • shunit2:支持POSIX sh的xUnit风格框架
  • sharness:Git使用的测试框架(兼容POSIX)

Common Pitfalls to Avoid

常见陷阱与规避方法

  • Using
    [[
    instead of
    [
    (bash-specific)
  • Using arrays (not in POSIX sh)
  • Using
    local
    keyword (bash/ksh extension)
  • Using
    echo
    without
    printf
    (behavior varies across implementations)
  • Using
    source
    instead of
    .
    for sourcing scripts
  • Using bash-specific parameter expansion:
    ${var//pattern/replacement}
  • Using process substitution
    <()
    or
    >()
  • Using
    function
    keyword (ksh/bash syntax)
  • Using
    $RANDOM
    variable (not in POSIX)
  • Using
    read -a
    for arrays (bash-specific)
  • Using
    set -o pipefail
    (bash-specific)
  • Using
    &>
    for redirection (use
    >file 2>&1
    )
  • 使用
    [[
    而非
    [
    (bash特定)
  • 使用数组(POSIX sh不支持)
  • 使用
    local
    关键字(bash/ksh扩展)
  • 使用
    echo
    而非
    printf
    (不同实现行为不同)
  • 使用
    source
    而非
    .
    加载脚本
  • 使用bash特定参数扩展:
    ${var//pattern/replacement}
  • 使用进程替换
    <()
    >()
  • 使用
    function
    关键字(ksh/bash语法)
  • 使用
    $RANDOM
    变量(POSIX不支持)
  • 使用
    read -a
    处理数组(bash特定)
  • 使用
    set -o pipefail
    (bash特定)
  • 使用
    &>
    进行重定向(应使用
    >file 2>&1

Advanced Techniques

高级技巧

  • Error Trapping:
    trap 'echo "Error at line $LINENO" >&2; exit 1' EXIT; trap - EXIT
    on success
  • Safe Temp Files:
    tmpfile=$(mktemp) || exit 1; trap 'rm -f "$tmpfile"' EXIT INT TERM
  • Simulating Arrays:
    set -- item1 item2 item3; for arg; do process "$arg"; done
  • Field Parsing:
    IFS=:; while read -r user pass uid gid; do ...; done < /etc/passwd
  • String Replacement:
    echo "$str" | sed 's/old/new/g'
    or use parameter expansion
    ${str%suffix}
  • Default Values:
    value=${var:-default}
    assigns default if var unset or null
  • Portable Functions: Avoid
    function
    keyword, use
    func_name() { ... }
  • Subshell Isolation:
    (cd dir && cmd)
    changes directory without affecting parent
  • Here-documents:
    cat <<'EOF'
    with quotes prevents variable expansion
  • Command Existence:
    command -v cmd >/dev/null 2>&1 && echo "found" || echo "missing"
  • 错误捕获
    trap 'echo "Error at line $LINENO" >&2; exit 1' EXIT; trap - EXIT
    (成功时移除陷阱)
  • 安全临时文件
    tmpfile=$(mktemp) || exit 1; trap 'rm -f "$tmpfile"' EXIT INT TERM
  • 模拟数组
    set -- item1 item2 item3; for arg; do process "$arg"; done
  • 字段解析
    IFS=:; while read -r user pass uid gid; do ...; done < /etc/passwd
  • 字符串替换
    echo "$str" | sed 's/old/new/g'
    或使用参数扩展
    ${str%suffix}
  • 默认值
    value=${var:-default}
    (当var未设置或为空时分配默认值)
  • 可移植函数:避免使用
    function
    关键字,使用
    func_name() { ... }
  • 子shell隔离
    (cd dir && cmd)
    (更改目录而不影响父shell)
  • Here-document
    cat <<'EOF'
    (带引号可防止变量扩展)
  • 命令存在性检查
    command -v cmd >/dev/null 2>&1 && echo "found" || echo "missing"

POSIX-Specific Best Practices

POSIX特定最佳实践

  • Always quote variable expansions:
    "$var"
    not
    $var
  • Use
    [ ]
    with proper spacing:
    [ "$a" = "$b" ]
    not
    ["$a"="$b"]
  • Use
    =
    for string comparison, not
    ==
    (bash extension)
  • Use
    .
    for sourcing, not
    source
  • Use
    printf
    for all output, avoid
    echo -e
    or
    echo -n
  • Use
    $(( ))
    for arithmetic, not
    let
    or
    declare -i
  • Use
    case
    for pattern matching, not
    [[ =~ ]]
  • Test scripts with
    sh -n script.sh
    to check syntax
  • Use
    command -v
    not
    type
    or
    which
    for portability
  • Explicitly handle all error conditions with
    || exit 1
  • 始终对变量扩展添加引号:使用
    "$var"
    而非
    $var
  • 使用
    [ ]
    时保持适当空格:
    [ "$a" = "$b" ]
    而非
    ["$a"="$b"]
  • 字符串比较使用
    =
    而非
    ==
    (bash扩展)
  • 加载文件使用
    .
    而非
    source
  • 所有输出使用
    printf
    ,避免
    echo -e
    echo -n
  • 算术运算使用
    $(( ))
    而非
    let
    declare -i
  • 模式匹配使用
    case
    而非
    [[ =~ ]]
  • 使用
    sh -n script.sh
    检查脚本语法
  • 可移植性检查使用
    command -v
    而非
    type
    which
  • 使用
    || exit 1
    显式处理所有错误情况

References & Further Reading

参考资料与进一步阅读

POSIX Standards & Specifications

POSIX标准与规范

Portability & Best Practices

可移植性与最佳实践

Tools & Testing

工具与测试