Linux 在给定时间内读取用户输入,否则退出
我正在编写一个脚本,用户应该在20秒内提供他/她的输入。如果未在该时间内提供,则脚本应退出Linux 在给定时间内读取用户输入,否则退出,linux,bash,shell,unix,Linux,Bash,Shell,Unix,我正在编写一个脚本,用户应该在20秒内提供他/她的输入。如果未在该时间内提供,则脚本应退出 countdown() ( # https://www.cyberciti.biz/faq/how-to-display-countdown-timer-in-bash-shell-script-running-on-linuxunix/ IFS=: set -- $* secs=$(( ${1#0} * 3600 + ${2#0} * 60 + ${3#0} )) while [
countdown()
(
# https://www.cyberciti.biz/faq/how-to-display-countdown-timer-in-bash-shell-script-running-on-linuxunix/
IFS=:
set -- $*
secs=$(( ${1#0} * 3600 + ${2#0} * 60 + ${3#0} ))
while [ $secs -gt 0 ]
do
sleep 1 &
printf "\r%02d:%02d:%02d" $((secs/3600)) $(( (secs/60)%60)) $((secs%60))
secs=$(( $secs - 1 ))
wait
done
echo
)
echo -n "Your answer : countdown "00:00:20" "; read readUserInput
用户应在20秒内提供其输入,如果未提供,则脚本应退出
countdown()
(
# https://www.cyberciti.biz/faq/how-to-display-countdown-timer-in-bash-shell-script-running-on-linuxunix/
IFS=:
set -- $*
secs=$(( ${1#0} * 3600 + ${2#0} * 60 + ${3#0} ))
while [ $secs -gt 0 ]
do
sleep 1 &
printf "\r%02d:%02d:%02d" $((secs/3600)) $(( (secs/60)%60)) $((secs%60))
secs=$(( $secs - 1 ))
wait
done
echo
)
echo -n "Your answer : countdown "00:00:20" "; read readUserInput
因此,20秒后读取超时
# the user should provide his/her input within 20 seconds
if ! read -r -t 20 input; then
# if its not provided then the script should exit
exit
fi
请注意,-t
读取的选项是对posix外壳的bash
扩展。在与posix兼容的shell上,我想我应该使用timeout
命令和从用户处读取的子shell,以及input=$(timeout 20sh-c'read-r input&&printf“%s\n”“$input”)
[想象问题OP never ask]:如何要求用户输入20秒超时,同时提供从20到0的计时器计数
在后台进程中显示倒计时。下面的实现使用SIGUSR1与后台进程通信,该停止了(好吧,使用SIGTERM不想工作得很好)。它还使用\e[s
和\e[u
ansi转义码将每个输入字符恢复到正确位置后的光标位置。TLDR:看起来很有趣
countdown() (
# https://www.cyberciti.biz/faq/how-to-display-countdown-timer-in-bash-shell-script-running-on-linuxunix/
local fmt=$1
local secs=$(($2+1))
trap exit SIGUSR1
printf "$fmt" "$(printf "%02d:%02d:%02d" "$((secs / 3600))" "$(( (secs / 60) % 60))" "$((secs % 60))")"
while ((secs--)); do
sleep 1 &
printf "\e[s\r$fmt\e[u" "$(printf "%02d:%02d:%02d" "$((secs / 3600))" "$(( (secs / 60) % 60))" "$((secs % 60))")"
wait
done
printf "\r%fmt" "00:00:00"
)
countdown_end() {
pkill -SIGUSR1 -P "$1" # sending SIGUSR1 hoping for gracefull exit
wait "$1"
}
timeout=5
countdown "Countdown %s: input: " "$timeout" &
child=$!
if ! read -r -t "$timeout" readUserInput; then
countdown_end "$child"
echo
exit
fi
countdown_end "$child"
echo "You inputted " "$readUserInput"
因此,read-t20input
no?@KamilCuk您能否与我们分享如何添加代码的示例,从user1获取值。删除所有代码。2.执行if!read-t20readuserinput;然后退出;fi
@KamilCuk不工作回显“从用户读取输入:”读取readUserInput如果!读取-t 20 readUserInput;然后退出;fi@KamilCuk是否有可能显示倒计时时间,如20 19 18 17…在弹出窗口上显示20秒,并显示您的倒计时结束和退出