在Linux/Unix shell脚本中如何显示倒计时

时间:2019-11-20 08:53:50  来源:igfitidea点击:

bash shell脚本上如何显示倒计时?

解决方案

先清除屏幕,然后通过tput在指定位置显示倒计时

clear
tput cup 10 5

shell计算字符串的长度的方法:

l=${#msg}

计算下一列的方法:

l=$(( l+5 ))

最后使用bash for循环显示倒计时:

for i in {30..01}
do
tput cup 10 $l
echo -n "$i"
sleep 1
done
echo

完整的代码如下

#!/bin/bash
zone_id="My-ID"
api_key="My_API_KEY"
email_id="My_EMAIL_ID"
row=2
col=2
urls="$@"
countdown() {
        msg="Purging ..."
        clear
        tput cup $row $col
        echo -n "$msg"
        l=${#msg}
        l=$(( l+$col ))
        for i in {30..1}
        do
                tput cup $row $l
                echo -n "$i"
                sleep 1
        done
}
# Do it
for u in $urls
do
     amp_url="${u}amp/"
     curl -X DELETE "https://api.cloudflare.com/client/v4/zones/${zone_id}/purge_cache" \
     -H "X-Auth-Email: ${email_id}" \
     -H "X-Auth-Key: ${api_key}" \
     -H "Content-Type: application/json" \
     --data "{\"files\":[\"${u}\",\"${amp_url}\"]}" &>/dev/null &&  countdown "$u"
 
done
echo

运行脚本:

./script.sh url1 url2

POSIX Shell版本

使用shell函数:

countdown()
(
  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
)

按如下方式运行:

countdown "00:00:10" 
countdown "00:00:30" 
countdown "00:01:42"