Saturday, January 31, 2009

Bash read command timed out feature

In bash scripting if you have a situation where you don't want to wait for user response forever, bash read command given an option (-t) which cause read command to time out in "number of seconds" specified with this -t option.

From read command man page:

-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.

-p prompt : Display prompt, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal.

Lets try a small one liner:

$ ans="y"
$ read -t 5 -p "Want to proceed ?(y/n)" ans; echo "You entered $ans"

Also notice the "$?" (exit status of last executed command) value in both the cases

a) When user has responded within that time
b) When its timed out

Its useful !!

1 comment:

Unknown said...

#Don't respond in 5 sec and let read timed out

$ read -t 5 -p "Want to proceed ?(y/n)" ans
Want to proceed ?(y/n)

#See this value
$ echo $?

#Lets respond within time
$ read -t 5 -p "Want to proceed ?(y/n)" ans
Want to proceed ?(y/n)y

#Now see,
$ echo $?

© Jadu Saikia