Skip to content
Advertisement

Bash – How to run code whenever USB device is connected

I am writing a bash script to automatically detect when my USB keyboard is plugged into my laptop (running Ubuntu 14), so I can change the keyboard layout automatically.

Here is my code so far (I got it from another post on Stack Overflow so I’m not 100% sure how it works)

JavaScript

I have got this to run on startup so far… But I’d like it to run every time a USB device is connected or disconnected.

It is important that I have it all run in one Bash script and not as a .rules file in …udev/… or anything. However, a single Python script will do just as well.

Advertisement

Answer

Thanks to ralf htp I was able to come up with the following solution. It has the following improvements:

  • It is not dependent on specific keyboards, it will treat all USB keyboards in the same way.
  • If the user manually switches to a different keyboard layout (one which is neither the default or the USB keyboard’s) it will not automatically switch it back to the default or USB layout.

Please feel free to improve this code at GitHub Gist

JavaScript
Advertisement