Skip to content

Instantly share code, notes, and snippets.

@jaytaylor jaytaylor/._README.md
Last active Jul 19, 2019

Embed
What would you like to do?
Bash shell programming snippets quick reference

Bash shell programming snippets

Quick references to common and useful bash programming snippets

#!/usr/bin/env bash
set -o errexit
set -o pipefail
set -o nounset
if [ "${1:-}" = '-v' ]; then
echo 'DEBUG: verbose mode enabled' 1>&2
set -o xtrace
shift
fi
die() {
echo "ERROR: $*" 1>&2
exit 1
}
usage() {
echo 'not yet implemented' 1>&2
}
main() {
if [[ "${1:-}" =~ ^(-h|--help)$ ]] ; then
usage
return 0
fi
}
if [ "${BASH_SOURCE[0]}" = "${0}" ] ; then
main "$@"
fi

Bash verbose xtrace mode

if [ "${1:-}" = '-v' ] ; then
    echo 'DEBUG: verbose mode enabled' 1>&2
    trap 'set +o xtrace' EXIT
    set -o xtrace
    shift
fi

Bash main()

Bash equivalent to if __name__ == '__main__': in Python.

if [ "${BASH_SOURCE[0]}" = "${0}" ] ; then
    main "$@"
fi

Bash pop last argument / reverse_shift

This can also be thought of as a reverse of the shift command.

Works for both scripts and functions.

Credit: Source

last="${@:$#}"

set -- "${@:1:$(($#-1))}"

trappend: Set or append command to trap signal handler

# trappend is like trap, with the addition  that if there is an existing trap
# already set, it will append the new command(s) without clobbering the
# pre-existing trap orders.
#
# n.b. Won't work for RETURN (hopefully this is somewhat obvious ;).
#
# usage: trappend cmds.. SIGNAL
trappend() {
    local sig
    local existing

    # n.b. Reverse-shift operation.
    sig="${*:$#}"
    set -- "${@:1:$(($#-1))}"

    if [ "${sig}" = 'RETURN' ] ; then
        echo 'ERROR: trappend: SIGNAL value cannot be "RETURN"' 1>&2
        return 1
    fi

    if [ -n "$(trap -p "${sig}")" ] ; then
        existing="$(trap -p "${sig}" | sed "s/^trap -- '\(.*\)' ${sig}\$/\1/");"
    fi

    # shellcheck disable=SC2064
    trap "${existing:-}$*" "${sig}"
}

Example usage

trappend 'echo hello 3' EXIT
trappend 'echo hello 4' EXIT

echo hello 0
echo hello 1

Output:

hello 0
hello 1
hello 3
hello 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.