From: pk on 11 Dec 2009 07:52
> I am trying to do the following in bash and don't even know if it is
> Do something if the 'Y' is pressed. However if any other key is pressed
> or if no key is pressed for 5 seconds.
> The first part is pretty easy with a simple read. However I have no idea
> where to start with the part where I want to let things happen if I do
> nothing for 5 seconds. A sleep would interupt the script in such a way
> that the 'read' part won't work.
> And read will wait for somthing to happen first.
> Anybody an idea? I do not even know where to start looking with google.
Well bash can do "read -t 5". See man bash for the details.
You can thus check, in the next statement, whether a key was pressed (and
then check if it's Y or not), or no key was pressed.
From: pk on 11 Dec 2009 10:25
> Got it working with the following:
> #set -x
> printf "Are you sure? You have 5 seconds to confirm with capital Y: "
> read -t 5 -n 1 CHAR
> if [ $CHAR = "Y" ]
> echo "Y pressed"
> echo "Nothing or at least not Y pressed. $CHAR"
If that matters to you, you can even distinguish between the two cases in
the "else" branch, by testing read's exit status.
From: pk on 11 Dec 2009 11:23
>>> Got it working with the following:
>>> #set -x
>>> printf "Are you sure? You have 5 seconds to confirm with capital Y: "
>>> read -t 5 -n 1 CHAR
>>> if [ $CHAR = "Y" ]
>>> echo "Y pressed"
>>> echo "Nothing or at least not Y pressed. $CHAR"
>> If that matters to you, you can even distinguish between the two cases in
>> the "else" branch, by testing read's exit status.
> I am not sure what you mean, but I am always willing to learn.
I mean in case you are actually interested to know whether the user pressed
a non-"Y" key, or did not press a key at all. See these examples:
$ read -t 5 foo # wait 5 seconds
$ echo $?
$ read -t 5 foo # enter something
$ echo $?
So in case the user didn't press any key, the exit status will be nonzero.
But that probably doesn't matter to you, as you only need to know if "Y" was
pressed or not.