Search code examples
linuxbashshell

How can I use Bash to listen to multiple input devices on Linux?


I'm trying to write a shell script to wait for input from any one of multiple devices, then from the input event determine which button was pressed and which device it came from.

In my case I want to get controller/joystick input, i.e., /dev/input/js0, /dev/input/js1 etc. For example print "press start to play", and then get the device path of first controller to respond.

I have found the below command using jstest, but it this does not work with multiple devices.

$ jstest --event /dev/input/js0 | grep -m 1 "type 1, time .*, number .*, value 1"
Event: type 1, time 2697465, number 0, value 1

Solution

  • Update: As per @jhnc's advice I've improved this by not parsing the output of ls

    Following @user1934428's suggestion to use a background process and wait, I came up with this solution.

    # loop through joystick devices
    for device in /dev/input/js*
    do
        # use jstest and grep to capture the start button (number 7)
        jstest --event $device | grep -m 1 "type 1, time .*, number 7, value 1" &
    done
    
    # wait for at least one of the background processes to finish then kill the others
    wait -n
    kill $(jobs -p)
    

    The below questions/answers also helped in coming up with this solution