Notifications when a command finishes running

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.

  • 14
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值