tehp
tehp

Reputation: 6384

Is there a way to bring terminal to front when command is finished?

Is there a way that I can force terminal to become the active window when a command is finished running?

It would be very useful when running lengthy commands or scripts to be notified somehow when they complete.

Alternatively, could I send a notification through macOS every time a command finishes?

Upvotes: 4

Views: 1860

Answers (2)

Ken Thomases
Ken Thomases

Reputation: 90531

Another thing to be aware of: if something beeps or rings the bell in a Terminal window or tab when it's in the background, it will bounce its Dock icon and badge it with the number of such beeps or bells. The badge is cleared when you switch to the affected window or tab.

In bash, you can beep using any of echo ^V^G (that's Control-V, Control-G), echo -n $'\a', or printf "\a". Don't know about zsh.

Upvotes: 4

mklement0
mklement0

Reputation: 437383

On macOS 10.8+, AppleScript supports the display notification command for displaying notifications (optionally with a sound).

Here's an example, using sleep 3 to represent a long-running shell command:

sleep 3; osascript -e 'display notification "Done!" with title "Long-running shell command" sound name "Hero"'

You could wrap this functionality in a shell function and add it to your ~/.zshrc file:

notifyWhenDone() {
  local msg=${1:-'Done!'} title=${2:-'Long-running shell command'} sound=${3:-'Hero'}
  osascript -e 'display notification "'"$msg"'" with title "'"$title"'" sound name "'"$sound"'"'
}

Note: To make this fully robust, you'd have to make sure that the content of optional arguments $1, $2, and $3 doesn't break the AppleScript command.

With this function in place:

sleep 3; notifyWhenDone

If you also want to activate Terminal.app on completion, append the following option to the arguments passed to osascript:
-e 'activate application "Terminal"'.

Upvotes: 5

Related Questions