Skip to content

Instantly share code, notes, and snippets.

@bprosnitz
Last active November 19, 2021 18:55
Show Gist options
  • Save bprosnitz/a155b40c8a61985565788f2acf414d43 to your computer and use it in GitHub Desktop.
Save bprosnitz/a155b40c8a61985565788f2acf414d43 to your computer and use it in GitHub Desktop.
bash: notify when long running command has finished
DURATION_FOR_NOTIFY=10
PROMPT_ID=$RANDOM
preexec () {
date +%s > /tmp/.time${PROMPT_ID}
echo $1 > /tmp/.cmd${PROMPT_ID}
}
postexec() {
OLD_TS=$(cat /tmp/.time${PROMPT_ID})
if [[ OLD_TS -eq "" ]]; then
return
fi
echo "" > /tmp/.time${PROMPT_ID}
NEW_TS=$(date +%s)
DURATION=`expr $NEW_TS - $OLD_TS`
if [[ ${DURATION} -ge ${DURATION_FOR_NOTIFY} ]]; then
CMD_NAME=$(cat /tmp/.cmd${PROMPT_ID})
notify-send "Command '${CMD_NAME}' has finished'"
fi
}
preexec_invoke_exec() {
[ -n "$COMP_LINE" ] && return
[ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return
preexec $(HISTTIMEFORMAT= history 2 | cut -d\ -f 4-)
}
PROMPT_COMMAND="postexec"
trap 'preexec_invoke_exec' DEBUG
@bas080
Copy link

bas080 commented Nov 19, 2021

I suggest an improvement and also respect other peoples PROMPT_COMMAND configurations and do the following:

PROMPT_COMMAND="postexec;$PROMPT_COMMAND"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment