10

When I have wait for slow commands (operations on large databases for example), I start doing something else and often don't notice for a long time that it has finished, wasting valuable time. I am looking for a way for the shell to alert me (by which I mean, run some custom command which I can determine) when a command which has been running for more than X seconds has finished and I got back the prompt.

I am using Bash, but solutions for other shells would be interesting as well.

Tgr
  • 3,133

4 Answers4

12

This script, if put in your .bashrc, will execute any command you like whenever the prompt returns after a long time executing a command - customize the "long time" (after the -gt) in seconds, and within the curly braces on the same line you can execute whichever commands you like. You could even send yourself an email with the Host on which this occured and the last executed command and its status code.

beep_if_long_time_past() {
    LAST_COMMAND_DURATION=$(($(date +%s) - ${LAST_COMMAND_TIME}))
    [[ ${LAST_COMMAND_DURATION} -gt 60 ]] && { echo "Took long, didn't it?" ; notify-send "I'm done after ${LAST_COMMAND_DURATION} seconds!"; }
    export LAST_COMMAND_TIME=
}

export PROMPT_COMMAND=beep_if_long_time_past
trap '[ -z ${LAST_COMMAND_TIME} ] && export LAST_COMMAND_TIME=$(date +%s)' DEBUG
Stefan Seidel
  • 10,855
6
slowcommand; echo -e "\a"

Works, but it is ugly and inconvenient to append the notification command by hand every time; also easy to forget. (A notification can be appended to an already running process with wait as this answer explains, but that is even uglier.)

Tgr
  • 3,133
2

I usually use a pop-up notification, xmessage tends to be available:

slowcommand; xmessage -center 'Job done!'

Or add a reminder (depends on the atd daemon):

echo 'xmessage -display :0 -center "Check on job"' | at 'now + 10 minutes'
Thor
  • 6,763
  • 1
  • 40
  • 44
1

I have created telert, a lightweight open-source tool that does exactly this. It lets you get a sound alert, desktop popup, or even a message on Telegram or Slack when a long-running command finishes.

Setting it up is quick and easy

pip install telert
telert config audio --set-default  # for sound
telert config desktop --set-default  # for popup
telert config telegram --token "<token>" --chat-id "<chat-id>" --set-default # for telegram

You can then use it with your long running commands in your script.

long_running_command | telert # Option 1
telert run long_running_Command # Option 2

Telert will time the command and send a notification to the provider channel when it completes with the execution time and exit code.

Mihir
  • 11