To achieve notifications when a command finishes running in a terminal on Ubuntu, you can utilize the notify-send
command which is part of the libnotify
package. This command allows you to create desktop notifications. You might need to install libnotify
if it’s not already installed on your system.
Here’s how to set it up and use it:
Step 1: Install libnotify-bin
(if not already installed)
First, you need to ensure that notify-send
is available on your system. Open a terminal and install libnotify-bin
by running:
sudo apt update
sudo apt install libnotify-bin
Step 2: Using notify-send
with commands
You can append notify-send
to any command you run in the terminal to get a notification when the command finishes executing. Here’s the basic syntax:
command; notify-send "Notification Title" "Command finished"
For example, if you’re running a script called script.sh
, you would use:
./script.sh; notify-send "Script Notification" "script.sh has finished running."
Step 3: Create an alias for convenience (optional)
If you find yourself frequently needing notifications, you can create an alias to make this process easier. Open your ~/.bashrc
or ~/.bash_aliases
file in a text editor, and add an alias like this:
alias notifycmd='notify-send "Terminal" "Command executed"'
Then, you can use this alias at the end of any command:
./script.sh; notifycmd
After editing your .bashrc
or .bash_aliases
, apply the changes by running:
source ~/.bashrc # or source ~/.bash_aliases
Step 4: Automating Notifications for All Commands (advanced)
If you want to automatically get notifications for every command you execute, you can customize your shell’s prompt command, but this is more complex and can be intrusive. It involves modifying the PROMPT_COMMAND
in bash to check the last command’s exit status and send a notification accordingly.
Here’s a basic implementation you can add to your ~/.bashrc
:
notify_command() {
status=$?
if [ $status -ne 0 ]; then
notify-send "Command failed" "Error Code: $status"
else
notify-send "Command completed" "Exited with success"
fi
}
PROMPT_COMMAND="notify_command; $PROMPT_COMMAND"
This script notifies you of the completion of every command, with a different message for success or failure based on the exit status.
Conclusion
Using notify-send
in this way can greatly enhance your productivity, especially for long-running commands, by alerting you the moment they complete. Remember, though, that for GUI notifications to work, you need to be running a desktop environment that supports them, which is typically the case with standard Ubuntu installations.