posix-shell-pro
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUse 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 keyword (use function-scoped variables carefully)
local - No ,
declare, ortypesetfor variable attributesreadonly - No operator for string concatenation
+= - No substitution
${var//pattern/replacement} - No associative arrays or hash tables
- No command (use
sourcefor sourcing files).
- 不使用数组(使用位置参数或分隔字符串)
- 不使用条件判断(仅使用
[[测试命令)[ - 不使用进程替换或
<()>() - 不使用大括号扩展
{1..10} - 不使用关键字(谨慎使用函数作用域变量)
local - 不使用、
declare或typeset设置变量属性readonly - 不使用运算符进行字符串拼接
+= - 不使用替换
${var//pattern/replacement} - 不使用关联数组或哈希表
- 不使用命令(使用
source来加载文件).
Approach
方法
- Always use shebang for POSIX shell
#!/bin/sh - Use for error handling (no
set -euin POSIX)pipefail - Quote all variable expansions: never
"$var"$var - Use for all conditional tests, never
[ ][[ - Implement argument parsing with and
while(nocasefor long options)getopts - Create temporary files safely with and cleanup traps
mktemp - Use instead of
printffor all output (echo behavior varies)echo - Use instead of
. script.shfor sourcingsource script.sh - Implement error handling with explicit checks
|| exit 1 - Design scripts to be idempotent and support dry-run modes
- Use manipulation carefully and restore original value
IFS - Validate inputs with and
[ -n "$var" ]tests[ -z "$var" ] - End option parsing with and use
--for safetyrm -rf -- "$dir" - Use command substitution instead of backticks for readability
$() - Implement structured logging with timestamps using
date - Test scripts with dash/ash to verify POSIX compliance
- 始终使用作为POSIX Shell的shebang
#!/bin/sh - 使用进行错误处理(POSIX不支持
set -eu)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 to invoke the system's POSIX shell
#!/bin/sh - 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: for OS detection
uname -s - Use instead of
command -v(more portable)which - Check for command availability:
command -v cmd >/dev/null 2>&1 || exit 1 - Provide portable implementations for missing utilities
- Use for existence checks (works on all systems)
[ -e "$file" ] - Avoid ,
/dev/stdin(not universally available)/dev/stdout - Use explicit redirection instead of (bash-specific)
&>
- 使用调用系统的POSIX Shell
#!/bin/sh - 在多个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: not
validate_inputcheck - 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_inputcheck - 为非显而易见的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 on untrusted input
eval - 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 for cleanup:
traptrap '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: not
/bin/rmrm
- 对所有变量扩展添加引号以防止单词拆分
- 操作前验证文件权限:
[ -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; } - 使用进行清理:
traptrap 'rm -f "$tmpfile"' EXIT INT TERM - 为敏感文件设置严格的umask:
umask 077 - 将安全相关操作记录到syslog或文件中
- 验证文件路径不包含意外字符
- 在安全关键脚本中使用命令的完整路径:如而非
/bin/rmrm
Performance Optimization
性能优化
- Use shell built-ins over external commands when possible
- Avoid spawning subshells in loops: use not
while readfor i in $(cat) - Cache command results in variables instead of repeated execution
- Use for multiple string comparisons (faster than repeated
case)if - Process files line-by-line for large files
- Use or
exprfor arithmetic (POSIX supports$(( )))$(( )) - Minimize external command calls in tight loops
- Use when you only need true/false (faster than capturing output)
grep -q - Batch similar operations together
- Use here-documents for multi-line strings instead of multiple echo calls
- 尽可能使用Shell内置命令而非外部命令
- 避免在循环中生成子shell:使用而非
while readfor i in $(cat) - 将命令结果缓存到变量中而非重复执行
- 使用进行多字符串比较(比重复
case更快)if - 对大文件逐行处理
- 使用或
expr进行算术运算(POSIX支持$(( )))$(( )) - 在紧凑循环中尽量减少外部命令调用
- 仅需要真假结果时使用(比捕获输出更快)
grep -q - 将相似操作批量处理
- 使用here-document处理多行字符串而非多次调用echo
Documentation Standards
文档标准
- Implement flag for help (avoid
-hwithout proper parsing)--help - 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, or parameter expansion for string splittingawk
由于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: exists,
[ -e file ]regular file,[ -f file ]directory[ -d dir ] - String Tests: empty,
[ -z "$str" ]not empty,[ -n "$str" ]equal[ "$a" = "$b" ] - Numeric Tests: equal,
[ "$a" -eq "$b" ]less than[ "$a" -lt "$b" ] - Logical: AND,
[ cond1 ] && [ cond2 ]OR[ cond1 ] || [ cond2 ] - Negation: not a file
[ ! -f file ] - Pattern Matching: Use not
case[[ =~ ]]
使用带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 may be restricted
/tmp - 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 to identify bash-specific constructs
checkbashisms - Array elimination: Convert arrays to delimited strings or positional parameters
- Conditional updates: Replace with
[[and adjust regex to[patternscase - Local variables: Remove keyword, use function prefixes instead
local - Process substitution: Replace with temporary files or pipes
<() - Parameter expansion: Use /
sedfor complex string manipulationawk - 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
- 评估:运行识别bash特定结构
checkbashisms - 移除数组:将数组转换为分隔字符串或位置参数
- 更新条件判断:将替换为
[[,并将正则表达式调整为[模式case - 局部变量:移除关键字,改用函数前缀
local - 进程替换:将替换为临时文件或管道
<() - 参数扩展:使用/
sed进行复杂字符串操作awk - 测试策略:逐步转换并持续验证
- 文档:记录任何POSIX限制或解决方案
- 逐步迁移:一次转换一个函数,彻底测试
- 回退支持:过渡期间如需维护双重实现
Quality Checklist
质量检查清单
- Scripts pass ShellCheck with flag (POSIX mode)
-s sh - 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, ,
[[, etc.)local - 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
- 脚本通过标志的ShellCheck检查(POSIX模式)
-s sh - 代码使用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 for POSIX mode validation
-s sh - shfmt: Shell formatter with option for POSIX syntax
-ln posix - checkbashisms: Detects bash-specific constructs in scripts (from devscripts)
- Semgrep: SAST with POSIX-specific security rules
- CodeQL: Security scanning for shell scripts
- ShellCheck:静态分析器,使用进行POSIX模式验证
-s sh - shfmt:Shell格式化工具,支持选项的POSIX语法
-ln 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 keyword (bash/ksh extension)
local - Using without
echo(behavior varies across implementations)printf - Using instead of
sourcefor sourcing scripts. - Using bash-specific parameter expansion:
${var//pattern/replacement} - Using process substitution or
<()>() - Using keyword (ksh/bash syntax)
function - Using variable (not in POSIX)
$RANDOM - Using for arrays (bash-specific)
read -a - Using (bash-specific)
set -o pipefail - Using for redirection (use
&>)>file 2>&1
- 使用而非
[[(bash特定)[ - 使用数组(POSIX sh不支持)
- 使用关键字(bash/ksh扩展)
local - 使用而非
echo(不同实现行为不同)printf - 使用而非
source加载脚本. - 使用bash特定参数扩展:
${var//pattern/replacement} - 使用进程替换或
<()>() - 使用关键字(ksh/bash语法)
function - 使用变量(POSIX不支持)
$RANDOM - 使用处理数组(bash特定)
read -a - 使用(bash特定)
set -o pipefail - 使用进行重定向(应使用
&>)>file 2>&1
Advanced Techniques
高级技巧
- Error Trapping: on success
trap 'echo "Error at line $LINENO" >&2; exit 1' EXIT; trap - EXIT - 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: or use parameter expansion
echo "$str" | sed 's/old/new/g'${str%suffix} - Default Values: assigns default if var unset or null
value=${var:-default} - Portable Functions: Avoid keyword, use
functionfunc_name() { ... } - Subshell Isolation: changes directory without affecting parent
(cd dir && cmd) - Here-documents: with quotes prevents variable expansion
cat <<'EOF' - 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} - 默认值:(当var未设置或为空时分配默认值)
value=${var:-default} - 可移植函数:避免使用关键字,使用
functionfunc_name() { ... } - 子shell隔离:(更改目录而不影响父shell)
(cd dir && cmd) - Here-document:(带引号可防止变量扩展)
cat <<'EOF' - 命令存在性检查:
command -v cmd >/dev/null 2>&1 && echo "found" || echo "missing"
POSIX-Specific Best Practices
POSIX特定最佳实践
- Always quote variable expansions: not
"$var"$var - Use with proper spacing:
[ ]not[ "$a" = "$b" ]["$a"="$b"] - Use for string comparison, not
=(bash extension)== - Use for sourcing, not
.source - Use for all output, avoid
printforecho -eecho -n - Use for arithmetic, not
$(( ))orletdeclare -i - Use for pattern matching, not
case[[ =~ ]] - Test scripts with to check syntax
sh -n script.sh - Use not
command -vortypefor portabilitywhich - Explicitly handle all error conditions with
|| exit 1
- 始终对变量扩展添加引号:使用而非
"$var"$var - 使用时保持适当空格:
[ ]而非[ "$a" = "$b" ]["$a"="$b"] - 字符串比较使用而非
=(bash扩展)== - 加载文件使用而非
.source - 所有输出使用,避免
printf或echo -eecho -n - 算术运算使用而非
$(( ))或letdeclare -i - 模式匹配使用而非
case[[ =~ ]] - 使用检查脚本语法
sh -n script.sh - 可移植性检查使用而非
command -v或typewhich - 使用显式处理所有错误情况
|| exit 1
References & Further Reading
参考资料与进一步阅读
POSIX Standards & Specifications
POSIX标准与规范
- POSIX Shell Command Language - Official POSIX.1-2024 specification
- POSIX Utilities - Complete list of POSIX-mandated utilities
- Autoconf Portable Shell Programming - Comprehensive portability guide from GNU
- POSIX Shell Command Language - 官方POSIX.1-2024规范
- POSIX Utilities - POSIX规定的完整工具列表
- Autoconf Portable Shell Programming - GNU提供的全面可移植性指南
Portability & Best Practices
可移植性与最佳实践
- Rich's sh (POSIX shell) tricks - Advanced POSIX shell techniques
- Suckless Shell Style Guide - Minimalist POSIX sh patterns
- FreeBSD Porter's Handbook - Shell - BSD portability considerations
- Rich's sh (POSIX shell) tricks - 高级POSIX Shell技巧
- Suckless Shell Style Guide - 极简主义POSIX sh模式
- FreeBSD Porter's Handbook - Shell - BSD可移植性注意事项
Tools & Testing
工具与测试
- checkbashisms - Detect bash-specific constructs
- checkbashisms - 检测脚本中的bash特定结构