Ubuntu – What code is executed when headphones are disconnected

headphonesmonitoringsoundcard

I want to execute a script on headphones disconnect but I resent the idea of constant polling of the status when there is already some code executed when it's changed.

Best Answer

In most systems if not all, ACPI can handle this event. To test that:

  1. Run acpi_listen
  2. Unplug & replug headphones, example output: (mic/ears share in same jack on my laptop)

    jack/headphone HEADPHONE unplug
    jack/microphone MICROPHONE unplug
    jack/headphone HEADPHONE plug
    jack/microphone MICROPHONE plug
    
  3. Put your-script.sh in /etc/acpi/

  4. Add an event trigger file for your script in /etc/acpi/events/

    event=jack/headphone HEADPHONE unplug
    action=/etc/acpi/your-script.sh
    

    Check the other files there to learn from.

  5. You may need to restart acpid service to reload changed rules in /etc/acpi/events/

    sudo service acpid restart
    

Reference: man acpid