Jay Taylor's notes
back to listing indexjaytaylor's Bash shell skeleton programming snippets quick reference · GitHub
[web search]
Original source (gist.github.com)
Clipped on: 2023-07-13
Instantly share code, notes, and snippets.
Last active
June 15, 2023 14:53
jaytaylor's Bash shell skeleton programming snippets quick reference
Safe for-loop for find
output
https://stackoverflow.com/a/9612232/293064
find '.' -print0 | while IFS= read -d '' -r line; do echo "line=${line}" done
Bash main()
Bash equivalent to if __name__ == '__main__':
in Python.
n.b. The '--'
part needs to be revisited. Yesterday (Sunday 2020-02-09) I was unable to reproduce the behavior previously observed in Kubernetes a few weeks ago.
if [ "${BASH_SOURCE[0]}" = "${0}" ] || [ "${BASH_SOURCE[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