If you are not familiar with how to show interactive prompt in Bash shell script, please read this article first. Typically “read” command is used to read the response from the user. By default, the “read” command waits forever for the user input. However the “read” command supports an option “-t” which makes it to wait specified number of seconds for the user input. If user hasn’t provided the complete input, the “read” command exits with non-zero value. Looks at the following example to understand the behaviour of “read” command.

[neo@techpulp ~]# read -p "u like bash (y/n)? " -t 1
u like bash (y/n)? [neo@techpulp ~]#
[neo@techpulp ~]# echo $?
1
[neo@techpulp ~]# read -p "u like bash (y/n)? " -t 1
u like bash (y/n)? y
[neo@techpulp ~]# echo $?
0
[neo@techpulp ~]#

In the above example, no input is given for one second so it caused “read” command to exit with code “1“.

The following sample script how it can be used.

[neo@techpulp ~]# cat yesno.sh
#!/bin/bash

read -p "Answer me in 5 seconds. Do you like blue color (yes/no)? " -t 5 ans

if [ "$?" != "0" ]; then
	echo
	echo "You didn't answer in 5 seconds. "
	exit 0
fi

if [ "$ans" == "yes" ]; then
	echo "YES: That's great. I like blue color too."
else
	echo "NO: Never mind."
fi

[neo@techpulp ~]#

The following shows what happens when the above script is executed.

[neo@techpulp ~]# sh yesno.sh
Answer me in 5 seconds. Do you like blue color (yes/no)?
You didn't answer in 5 seconds.
[neo@techpulp ~]# sh yesno.sh
Answer me in 5 seconds. Do you like blue color (yes/no)? yes
YES: That's great. I like blue color too.
[neo@techpulp ~]# sh yesno.sh
Answer me in 5 seconds. Do you like blue color (yes/no)? no
NO: Never mind.
[neo@techpulp ~]#