fcm
fcm

Reputation: 1331

bash, non-blocking stdin/console input

I will like to write (using bash) something like

while no_user_key_pressed
{
  do_something....
}

There are a few options using C++, Java, ncurses and others o/s specific. I want a simple bash portable function.

^c interrupt should be used to kill the remaining code. Imagine something like: 'Press any key to stop test'

Upvotes: 1

Views: 826

Answers (2)

cdarke
cdarke

Reputation: 44354

You can use a small timeout on read -t.

The drawback is that the user must press < RETURN >, not "any key".

For example:

while ! read -t 0.01
do
    echo -en "$(date)\r"
done
echo "User pressed: $REPLY"

Tested on bash 3.2 (OS X)

The ! is because read returns a failure (false) if the timeout expires.

Upvotes: 1

l0b0
l0b0

Reputation: 58788

You can trap Ctrl-c in a way that does not kill the remaining code:

$ cat test.sh 
#!/usr/bin/env bash

trap 'break' INT

while true
do
    date
    sleep 1
done

echo done
$ ./test.sh 
Tue 28 Jun 12:01:22 UTC 2016
Tue 28 Jun 12:01:23 UTC 2016
Tue 28 Jun 12:01:24 UTC 2016
^Cdone

Upvotes: 1

Related Questions