我正在用Bash创建一个简单的问答游戏。我想要在一定的时间限制内运行问题。如何实现?谢谢。
我尝试使用这个命令:
sleep 2m && kill $$ &
但它会终止整个脚本。 另外:我想显示一个“时间到了”的短语。
与您最初的尝试类似,考虑创建一个子进程,使其休眠并发送一个信号,但这一次是可以被捕获的信号:
handle_hup() {
echo "Times up"
# do more things
}
trap handle_hup SIGHUP
mypid=$$
(sleep 2m && kill -HUP $mypid)&
echo "Quiz question: ..."
由于您没有展示完整的代码或需求,因此在此仅提供一小段代码,它将等待用户输入10秒钟,否则将打印用户已超时,您可以将其视为起点,并根据需要调整到您的脚本中。
read -t 10 -p "User, please enter your Input or it will time out in 10 seconds." ; echo ; date
MyFunction "${MyArguments[@]}" & # trailing ampersand (&) causes MyFunction to execute in background (with current environment)
zPid="$!" # bash $! provides the most recent background process id
timeout 2s bash -c wait $zPid # wait for MyFunction to finish (timeout after 2 seconds)
if [[ 124 = "$?" ]]; then # see man timeout for other error codes
echo "MyFunction timed out."
fi