Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Bash read with a timeout?

Tags:

bash

io

timeout

I can ask the user to press Enter by using read, and have him wait by calling sleep. But I can’t think of a way of doing both at the same time. I would like the user to be given the choice:

Press Ctrl+C to Cancel, Enter to continue or just wait 10 seconds

How can I do that?

like image 921
qdii Avatar asked Feb 28 '12 14:02

qdii


People also ask

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What is bash timeout?

timeout is a command-line utility that runs a specified command and terminates it if it is still running after a given period of time.

How do you read in bash?

Bash read Built-in The first word is assigned to the first name, the second one to the second name, and so on. The general syntax of the read built-in takes the following form: read [options] [name...] To illustrate how the command works, open your terminal, type read var1 var2 , and hit “Enter”.


1 Answers

In bash, read has a -t option where you can specify a timeout. From the manpage:

read [-ers] [-u fd] [-t timeout] [-a aname] [-p prompt] [-n nchars] [-d delim] [name ...]

-t timeout: cause read to time out and return failure if a complete line of input is not read within timeout seconds. This option has no effect if read is not reading input from the terminal or a pipe.

Transcript below (without hitting ENTER):

$ date ; read -t 10 -p "Hit ENTER or wait ten seconds" ; echo ; date Tue Feb 28 22:29:15 WAST 2012 Hit ENTER or wait ten seconds Tue Feb 28 22:29:25 WAST 2012 

Another, hitting ENTER after a couple of seconds:

$ date ; read -t 10 -p "Hit ENTER or wait ten seconds" ; date Tue Feb 28 22:30:17 WAST 2012 Hit ENTER or wait ten seconds Tue Feb 28 22:30:19 WAST 2012 

And another, hitting CTRL-C:

$ date ; read -t 10 -p "Hit ENTER or wait ten seconds" ; echo ; date Tue Feb 28 22:30:29 WAST 2012 Hit ENTER or wait ten seconds 
like image 139
paxdiablo Avatar answered Sep 19 '22 22:09

paxdiablo