Skip to content

Instantly share code, notes, and snippets.

@Saruspete
Created March 2, 2021 21:58
Show Gist options
  • Save Saruspete/ef9bf8f5693a487568bf640d53dd945f to your computer and use it in GitHub Desktop.
Save Saruspete/ef9bf8f5693a487568bf640d53dd945f to your computer and use it in GitHub Desktop.
bash pre/post exec hooks
# Some placeholders
typeset -i _BASHEXEC_PREEXECTIME=0
typeset _BASHEXEC_PREEXECCMD=""
function bashexec_post {
# Don't display anything if we didn't ran anything
if [[ -n "$_BASHEXEC_PREEXECCMD" ]]; then
echo "Took $((${SECONDS:-$(date +%s)} - $_BASHEXEC_PREEXECTIME ))s to run '$_BASHEXEC_PREEXECCMD'"
fi
# Reset the commands
_BASHEXEC_PREEXECCMD=""
}
function bashexec_pre {
# Skip the prompt_command itself
[[ "${BASH_COMMAND%% *}" == "${PROMPT_COMMAND%% *}" ]] && return
# Register the start-time + command (called once for each piped command)
_BASHEXEC_PREEXECTIME="${SECONDS:-$(date +%s)}"
_BASHEXEC_PREEXECCMD+="${_BASHEXEC_PREEXECCMD:+ | }$BASH_COMMAND"
}
PROMPT_COMMAND='bashexec_post $?'
trap 'bashexec_pre' DEBUG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment