Bash

Tips

Fail Fast

set -Eeuo pipefail

Cleanup

trap cleanup SIGINT SIGTERM ERR EXIT

cleanup() {
  trap - SIGINT SIGTERM ERR EXIT
  # script cleanup here
}

Job Control

$ set -o monitor  # enable script job control
$ trap 'echo "child died"' CHLD   # get notification when a child exits

文件

Style

範例

取得目前檔案的資料夾:

echo $(dirname $0)

如果有值 A 就使用值 A,不然使用值 B:

VAR1="${VAR1:-default value}"

VAR2="test"
VAR1="${VAR2:-default value}"

更多應用

簡易 supervisor

while true; do
    (ps aux | grep MYPROG > /dev/null) || \
        MYPROG --start
    sleep 1
done

取得目前程式碼路徑

等待網路通到外面

until ping -c 1 8.8.8.8; do
    echo "Network is not good, waiting"
    sleep 1
done

利用函式來讓 Script 更容易讀

has_myprog() {
    ps aux | grep myprog
}

init_myprog() {
    myprog --daemon
}

# if myprog is not running, init one
has_myprog || init_myprog

避免程式 block 住

CMD="sleep 10"
timeout 3s ${CMD}

Logging

log() {
    # style 1:
    # echo $1

    # style 2:
    TIME=$(date -u +"%Y-%m-%d|%H:%M:%S|%N")
    echo "[${TIME}]$1"
}

debug() {
    log "[  DEBUG] $1"
}

info() {
    log "[   INFO] $1"
}

warning() {
    log "[WARNING] $1"
}

error() {
    log "[  ERROR] $1"
}

參考