Command Line – Execute a Script When an Application Makes a Notification

command linedbusnotify-send

I searched quiet a bit but all the articles and answers only tell you how to create your own notification. What I want to do is to keep track of all the notifications made by all the applications, and execute a particular script every time a particular notification is made.

I will write my program to do this. All I need help with is how to 'intercept' the notifications.

Best Answer

Use (and identify) notifications to trigger subsequent actions

If we edit the proposed snippet in this very nice answer a bit, we can write the called notification to a file:

dbus-monitor "interface='org.freedesktop.Notifications'" | grep --line-buffered "string" | grep --line-buffered -e method -e ":" -e '""' -e urgency -e notify -v | grep --line-buffered '.*(?=string)|(?<=string).*' -oPi | grep --line-buffered -v '^\s*$' | xargs -I '{}' echo {} > file.txt

or otherwise use it to trigger subsequent actions.

An example

If we edit the snippet to run a script when a notification pops up:

dbus-monitor "interface='org.freedesktop.Notifications'" | grep --line-buffered "string" | grep --line-buffered -e method -e ":" -e '""' -e urgency -e notify -v | grep --line-buffered '.*(?=string)|(?<=string).*' -oPi | grep --line-buffered -v '^\s*$' | xargs -I '{}' /bin/bash /path/to/script.sh {}

and script.sh is:

#!/bin/bash
string=$1
match="een aap op een fiets"
if [[ $string == $match ]]
  then
    gedit
fi

Then, every time, if the notification matches "een aap op een fiets":

enter image description here

gedit will open :)

enter image description here

Note

Although the code works perfectly to intercept the notification to trigger any kind of action, I found no way to identify the pid that called the notification.