Ubuntu – Using acpi_listen command in a shell script


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

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

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