Ubuntu – Using acpi_listen command in a shell script

acpibashheadphonesscriptssound

I am on UBuntu 16.04. I have asked a question here regarding headphones plug unplug event. What I tried didn't work. I want to use acpi_listen command to listen to headphones connected event and display a message using notify-send. How to use acpi_listen in a shell script?

Best Answer

Writing script like that is fairly simple - you need to pipe acpi_listen to while IFS= read -r line ; do ... done structure, and take care of handling the events within that structure. The read shell builtin command will wait for a line of text from acpi_listen and processing will occur when the if statement sees that the line contains appropriate text. Alternatively, one could use case statement for better portability of the script.

Here's the simple script I personally would use. Tested on Ubuntu 16.04 LTS

#!/bin/bash
acpi_listen | while IFS= read -r line;
do
    if [ "$line" = "jack/headphone HEADPHONE plug" ]
    then
       notify-send "headphones connected"
       sleep 1.5 && killall notify-osd
    elif [ "$line" = "jack/headphone HEADPHONE unplug" ]
    then
       notify-send "headphones disconnected"
       sleep 1.5 && killall notify-osd
    fi
done

Note that if you plan to run this from cron job or via /etc/rc.local, you would need to export your DBUS_SESSION_BUS_ADDRESS for notify-send to work.

Related Question