How to timeout user input in Linux Bash Shell ?
In Linux, we use read command to take the user input.
However sometimes, we may need to timeout the user input to automate the script execution in case no one is available.
For this, we can use timeout option of read command.
Timeout User Input
### Timeout in 5 seconds if no input received. [root@nglinux ~]# read -t5 -p "Enter Your Name: "; echo Enter Your Name: [root@nglinux ~]#
In the above command, we have used “-t” option to set timeout to 5 seconds.
From the man page of timeout, we can read its description as follows:
-t timeout
Cause read to time out and return fail-
ure if a complete line of input is not
read within timeout seconds. timeout
may be a decimal number with a frac-
tional portion following the decimal
point. This option is only effective
if read is reading input from a termi-
nal, pipe, or other special file; it
has no effect when reading from regular
files. If timeout is 0, read returns
success if input is available on the
specified file descriptor, failure oth-
erwise. The exit status is greater
than 128 if the timeout is exceeded.
Hence we can use this option and mention number of seconds after which we want the script to timeout and proceed further.
