I have been partially successful with this, but I am stuck. Here is my script:

I want to prompt the user, wait for input from a USB gamepad, and then execute a command based on which button is pressed.

if lsusb | grep -q '0583:2060'
  echo "press the A button"
  if jstest --event /dev/input/js0 | grep -q "number 0, value 1"
    echo "you pressed the A button"
    echo "you pressed the NOT A button"

It checks for the gamepad being connected just fine. It also checks the jstest and echos "you pressed the A button" when I press the A button.

I can't get it to execute the "else" part in this situation though, as grep filters only "button 0, value 1" from jstest (the A button), which means if I am not pressing the A button jstest is piping NOTHING to grep, it always waits for the A button.

I was thinking maybe there was some way to do:

grep -q "number ., value 1" 

which will return ANY button being pressed, and then have different commands executed based on what what grep shows. I thought I could use a case statement for this, but I can't get jstest to work with case.

I feel like jstest isn't meant for this kind of stuff, only to test, but extensive googling has shown me no other options for interacting with a game pad through a script.

How can I make a shell script that prompts the user, waits for a button press, then executes different commands based on which button was pressed?

  • I'm not sure I understand what's going on; if you press a button other than "A", what does the jstest command output? – Jeff Schaller Mar 13 '17 at 11:13
  • Jstest starts a "test" program showing the status of all controller buttons, at once. The "--event" part of the command instead makes it shows one line for every event, key press and release. Grepping it with "number 0, value 1" literally makes it only output something when button 0's value is 1 (pressing the A button). If I press/release B, X, R, etc, jstest doesn't do anything. It is still sitting, waiting, normally blocking the terminal until it shows "number 0, value 1". – rhcpepper Mar 21 '17 at 1:19

You need to get grep to output the matching text, and stop after a match. You also need to filter events a bit more thoroughly, since you’re only interested in events of type 1 (buttons):

jstest --event /dev/input/js0 | grep -m 1 "type 1, time .*, number .*, value 1"

This will keep jstest running until you press a button, then output the event information. You can process this using read to find the number of the button that was pressed:

jstest --event /dev/input/js0 | grep -m 1 "type 1, time .*, number .*, value 1" | read _ _ _ _ _ _ number _ _
if [ "${number%%,*}" -eq 0 ]
    echo "You pressed the A button."
    echo "You pressed a button other than A."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.