2

I have a bash script that starts an external program (evtest) twice.

#!/bin/bash

echo "Test buttons on keyboard 1"
evtest /dev/input/event1

echo "Test buttons on keyboard 2"
evtest /dev/input/event2

As far as I know, evtest can be terminated only via Ctrl-C. The problem is that this terminates the parent script, too. That way, the second call to evtest will never happen.

How can I close the first evtest without closing the script, so that the second evtest will actually run?

Thanks!

P.S.: for the one that want to ask "why not running evtest manually instead of using a script?", the answer is that this script contains further semi-automated hardware debug test, so it is more convenient to launch the script and do everything without the need to run further commands.

1 Answer 1

6

You can use the trap command to "trap" signals; this is the shell equivalent of the signal() or sigaction() call in C and most other programming languages to catch signals.

The trap is reset for subshells, so the evtest will still act on the SIGINT signal sent by ^C (usually by quiting), but the parent process (i.e. the shell script) won't.

Simple example:

#!/bin/sh

# Run a command command on signal 2 (SIGINT, which is what ^C sends)
sigint() {
    echo "Killed subshell!"
}
trap sigint 2

# Or use the no-op command for no output
#trap : 2

echo "Test buttons on keyboard 1"
sleep 500

echo "Test buttons on keyboard 2"
sleep 500

And a variant which still allows you to quit the main program by pressing ^C twice in a second:

last=0
allow_quit() {
    [ $(date +%s) -lt $(( $last + 1 )) ] && exit
    last=$(date +%s)
}
trap allow_quit 2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.