Bash最佳实践

Bash最佳实践

基本规则

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
#!/usr/env/bin bash

## 增加TRACE调试
[[ "$TRACE" ]] && set -x 

## 快速失败并检查退出状态
set -eo pipefail

## 判断
[[ x > 2]] && echo x

## 获取脚本绝对路径
ROOT_PATH=$(cd $(dirname $BASH_SOURCE); pwd)

## 函数定义
myfunc() {
     declare desc="description"  ##函数描述

}
## 使用反射提取函数描述
eval $(type FUNCTION_NAME | grep 'declare desc=') && echo "$desc"

## 定参函数
regular_func() {
    ## 判断参数个数
    if [[ $# != 3 ]]; then  
        echo "Parameter incorrect."
        return 1
    fi
    declare arg1="$1" arg2="$2" arg3="$3"

    # ...
}

## 变参函数
variadic_func() {
    local arg1="$1"; shift
    local arg2="$1"; shift
    local rest="$@"

    # ...
}

## 测试退出代码(-q静音输出)
if grep -q 'foo' somefile; then
  ...
fi

## 测试输出( -m1 限制一个结果)
if [[ "$(grep -m1 'foo' somefile)" ]]; then
  ...
fi


func(){
    #do sth## 并行化执行func
for((i=0; i<10; i++))do
    func &   
done
wait

## 函数调用及返回
func(){
    echo "2333"
}
res=$(func) #获取函数返回

## 间接引用
echo ${!VAR1}

## 错误
err() {
  echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $*" >&2
}

# DO use 'here document's
cat >a_file  <<END
I am an exceptionally long
string.
END


# Long commands
command1 \
  | command2 \
  | command3 \
  | command4

## 使用main
func1(){
    #do sth
}

func2(){
    #do sth
}

main(){
    func1
    func2
}

main "$@"

参考

  1. Bash 最佳实践和技巧

  2. 编写Shell脚本的最佳实践

  3. styleguide | Style guides for Google-originated open-source projects

updatedupdated2024-05-102024-05-10