From: pk on
houghi wrote:

> I am trying to do the following in bash and don't even know if it is
> possible:
>
> 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
houghi wrote:

> Got it working with the following:
>
> #!/bin/bash
> #set -x
> printf "Are you sure? You have 5 seconds to confirm with capital Y: "
> read -t 5 -n 1 CHAR
> echo
> if [ $CHAR = "Y" ]
> then
> echo "Y pressed"
> else
> echo "Nothing or at least not Y pressed. $CHAR"
> fi

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
houghi wrote:

>>> Got it working with the following:
>>>
>>> #!/bin/bash
>>> #set -x
>>> printf "Are you sure? You have 5 seconds to confirm with capital Y: "
>>> read -t 5 -n 1 CHAR
>>> echo
>>> if [ $CHAR = "Y" ]
>>> then
>>> echo "Y pressed"
>>> else
>>> echo "Nothing or at least not Y pressed. $CHAR"
>>> fi
>>
>> 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 $?
142
$ read -t 5 foo # enter something
abc
$ echo $?
0

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.
 | 
Pages: 1
Prev: unix WHO command
Next: Use of 'set'