Re: [opensuse] Quick bash question - testing for the presence of keyboard input without pausing a loop?



David C. Rankin wrote:
Listmates,

I'm stuck. I would like to write a bash routine that tests for the presence of a user keypress ('q' or 'e') to exit a loop from within the loop without stopping the loop to wait like with read. Basically just execute the loop until the user presses a key, any key, to stop it. I can't figure out how do that will a keypress.

As a work around, I'm using a basic file ".runmcelog" file for that purpose:

while [ -f "/home/david/.runmcelog" ]; do
sudo /usr/sbin/mcelog --k8
done


I would fork off the rest of the processing code in the background.


Like this

run_processing_code &


(by moving it to a new shell script...
all of your variable and environment
WILL be inherited)

The new shell does the processing:
and either runs a loop

while [ ! -f $STOPFILE ]
do
something
done

or more simply:

cleanup_func()
{
clean-up code goes here
}

trap $MYSIG cleanup_func()


for (;;)
do
something
done

# cleanup_func() will actually execute HERE
exit


Or you can be more sophisticated, and build a signal
catcher using the built-in command trap
...but that's probably overkill for this.

The syntax for trap is like this
trap signo action



Meanwhile, the original shell does this:

CHILD=$!
READ $A
touch $STOPFILE # or send a signal to using:
# kill -$MYSIG $CHILD
rm -f $STOPFILE # clean up our mess, ignore non-existance errors
exit

--
To unsubscribe, e-mail: opensuse+unsubscribe@xxxxxxxxxxxx
For additional commands, e-mail: opensuse+help@xxxxxxxxxxxx



Relevant Pages

  • Re: Bash traps - while emitting ERR trap
    ... >> trap cleanup EXIT ERR ... >> while loop. ...
    (comp.unix.shell)
  • Re: [opensuse] Quick bash question - testing for the presence of keyboard input without pausing
    ... I would like to write a bash routine that tests for the presence of a user keypress to exit a loop from within the loop without stopping the loop to wait like with read. ... I'm using a basic file ".runmcelog" file for that purpose: ...
    (SuSE)
  • Re: Control-C behavior
    ... look at using a trap.. ... exit - you can set whatever value you want but i chose 11. ... for loop and then set the default trap value for a signal 2. ... When I hit Control-C, I want the top-level script to ...
    (comp.unix.shell)
  • Re: Control-C behavior
    ... look at using a trap.. ... exit - you can set whatever value you want but i chose 11. ... for loop and then set the default trap value for a signal 2. ... When I hit Control-C, I want the top-level script to ...
    (comp.unix.shell)
  • Bash traps - while emitting ERR trap
    ... echo "ENTER cleanup" ... echo "Entering while loop" ... If I remove the EXIT from the trap statement then I get the following ...
    (comp.unix.shell)