A Hacker News jóvoltából olvastam egy hasznos bejegyzést1 shell szkriptek írásával kapcsolatban. Megjegyzendő: egyetértek azzal, hogy a szervereken a bash a lingua franca, de saját célokra szívesebben használok fish-t (vagy Perlt).

A javasolt sablon bash szkriptekhez (némi módosítással):

#!/usr/bin/env bash

# -e: when a command fails, bash exits instead of continuing
set -o errexit
# -u: this will make the script fail, when accessing an unset variable
set -o nounset
# when a command in a pipeline fails, the whole pipeline fails
set -o pipefail
# -x: one can now enable debug mode
if [[ -n "${TRACE-}" ]]; then
    set -o xtrace
fi

# accept multiple ways that users can ask for help
if [[ "${1-}" =~ ^-*h(elp)?$ ]]; then
    cat << USAGE
Usage: $(basename $0) arg-one arg-two

This is an awesome bash script to make your life better.

USAGE
    exit
fi

# change to the script’s directory
cd "$(dirname "$0")"

# redirect error messages to stderr
err() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')]: $*" >&2
}

main() {
    #  use local variables in functions
    local i=foo
    echo Doing awesome stuff...
    err On no! An error occured!
    exit 1
}

main "$@"

A témához kapcsolódóan említést érdemel ez a Bash Style Guide és a Google-féle Shell Style Guide is. Továbbá:


  1. Shrikant Sharat Kandula: Shell Script Best Practices. sharats.me, 2022-10-27. ↩︎