How to put time limit in bash

Viewed 1852

I'm creating a simple quiz game in bash. I want to run the question with a certain time limit. How to do that? TIA

I tried using this command:

sleep 2m && kill $$ & 

but it terminates the whole script. Also: I want to display a "times up" phrase

3 Answers

The timeout command may do what you want. e.g.

$ timeout 120 your-game-command

You can check the exit status to know if the command timed out as per the docs:

If the command times out, then exit with status 124

Similar to your original attempt, consider creating a subprocess that sleeps and sends a signal but this time one that you catch:

handle_hup() {
  echo "Times up"
  # do more things
}

trap handle_hup SIGHUP

mypid=$$
(sleep 2m && kill -HUP $mypid)&

echo "Quiz question: ..."

Since you haven't showed complete code or requirement, so providing a small piece of code only here which will wait for user's input for 10 seconds else it will print that user has timed out, you could take it as a start up point and could adjust into your script accordingly.

read -t 10 -p "User, please enter your Input or it will time out in 10 seconds." ; echo ; date
Related