使用带-t标志的read时,是否可以显示剩余时间?

时间:2015-01-14 00:02:58

标签: bash unix

我的输入会在几秒钟后超时,但为了减少震动,我希望它显示剩余的时间。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

我不认为可以使用read -t完成此操作,但此脚本会在另一行上完成倒计时作为后台进程:

#!/bin/bash

function displayCountdown {
  ((remaining=$1))
  while [ $remaining -gt 0 ]
  do
    tput sc # save cursor pos
    tput cuu1 # go up one line
    tput cub 80 # go 80 chars left
    tput el # clear to eol
    ( echo -n "$remaining second(s) remaining" ) >&2
    tput rc # restore saved cursor pos
    ((remaining=remaining-1))
    sleep 1
  done
  echo
}

NUM_SECONDS=5

## the first echo is needed
echo ; displayCountdown $NUM_SECONDS & read -t $NUM_SECONDS ; RC=$? ; kill -9 $! ; wait $! 2>/dev/null

echo "Got ($RC): $REPLY"

exit 0

它并不完美。例如,当按下删除键时,它有时会产生^R并稍微弄乱终端。但是,如果您决定使用此功能,可能会有一些stty设置可用于解决此问题。

我在Mac上试过这个。我还没在Linux上试过这个。