Skip to content

Instantly share code, notes, and snippets.

@pbkwee
Last active September 3, 2024 02:30
Show Gist options
  • Save pbkwee/ad508f960a5c2c9ef3e00a0d6bb60782 to your computer and use it in GitHub Desktop.
Save pbkwee/ad508f960a5c2c9ef3e00a0d6bb60782 to your computer and use it in GitHub Desktop.
Function to return the last return code of a set of pipes. e.g. cat blah | sed blah | awk blah | mysql and you want to know if the mysql command worked ok.
# As an alternative to the remembering the following syntax:
# true | true | true; echo ${PIPESTATUS[${#PIPESTATUS[@]}-1]} => 0
# true | true | false; echo ${PIPESTATUS[${#PIPESTATUS[@]}-1]} => 1
#
# from bash 4.2 you can also do (more simply):
# true | true | false; echo ${PIPESTATUS[-1]} => 1 (and also: -bash: PIPESTATUS: bad array subscript)
#
# e.g. true | true | true; lastpipestatusretval && echo worked
# e.g. true | true | false; ! lastpipestatusretval && echo failed
# + tmppipestatus=('0' '0' '0')
# + local pipelen=2
# + '[' -z 2 ']'
# + '[' 2 -lt 1 ']'
# + tmppipestatus=0
# + return 0
function lastpipestatusretval() {
# echo ${PIPESTATUS[@]}
# 0 0 0 0 0 1
# ${#PIPESTATUS[@]} => length => 6
local tmppipestatus=(${PIPESTATUS[@]})
local pipelen=$(( ${#tmppipestatus[@]} -1 ))
[ -z "$pipelen" ] && return 1
[ $pipelen -lt 1 ] && return 1
# get last value
tmppipestatus="${tmppipestatus[ $pipelen ]}"
return $tmppipestatus
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment