POSIX Shell 缩进格式规范推荐

POSIX shell 脚本的缩进格式虽然没有官方标准,但有以下广为接受的实践规范:

基本缩进规则

1. 缩进大小

  • 推荐使用 2 或 4 个空格
  • 避免使用制表符(Tab)以保证跨环境一致性
# 好的示例 - 2空格缩进
if [ "$var" = "value" ]; then
  echo "Condition met"
  perform_task
fi

# 好的示例 - 4空格缩进
if [ "$var" = "value" ]; then
    echo "Condition met"
    perform_task
fi

2. 代码块缩进

# if/then/else
if condition; then
    command1
    command2
elif other_condition; then
    command3
else
    command4
fi

# for 循环
for item in $list; do
    process "$item"
    another_command
done

# while 循环
while condition; do
    process_data
    update_state
done

# case 语句
case $variable in
    pattern1)
        command1
        command2
        ;;
    pattern2)
        command3
        ;;
    *)
        default_command
        ;;
esac

3. 函数定义

my_function() {
    local var1="$1"
    local var2="$2"

    if [ -z "$var1" ]; then
        echo "Error: var1 is empty"
        return 1
    fi

    process_data "$var1" "$var2"
}

高级格式规范

4. 管道和多行命令

# 长管道命令
find /path -name "*.txt" \
    | grep -v "temp" \
    | sort -r \
    | head -10

# 复杂命令
curl -s -X GET \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    "https://api.example.com/data"

5. heredoc 缩进

# 缩进的 heredoc (<<- 允许前导制表符)
if [ "$use_heredoc" = "yes" ]; then
    cat <<- EOF
    This is a heredoc
    With indented content
    EOF
fi

最佳实践建议

6. 一致性规则

  • 选择一种风格并在整个项目中保持统一
  • 团队项目应制定并遵守共同的编码规范
  • 使用 shellcheck 进行语法检查

7. 文件头格式

#!/bin/sh
#
# 脚本名称: deployment.sh
# 描述: 应用部署脚本
# 作者: 姓名
# 创建日期: 2024-01-01
#
# 用法: ./deployment.sh [environment]
# 参数: environment - 部署环境 (prod/staging)
#

set -euo pipefail  # 严格模式

8. 注释规范

# 单行注释
## 重要说明使用双井号
# 
# 多行注释块
# 用于描述复杂逻辑
#

: '
这也是多行注释的
一种替代方式
'

工具推荐

格式化工具

  • shfmt: 自动格式化 shell 脚本
  • beautysh: 另一个 shell 格式化工具
  • shellcheck: 静态分析工具(不格式化但检查语法)

.editorconfig 示例

# .editorconfig
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.sh]
indent_style = space
indent_size = 2

选择最适合你项目的缩进风格并保持一致性是最重要的原则。


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish