如何在Linux/Unix上运行的bash shell脚本中显示倒数计时器

时间:2020-01-09 14:17:04  来源:igfitidea点击:

如何在清除CDN网络缓存之前显示倒计时。
在Linux或Unix bash shell脚本上,是否存在现有命令来显示从30..1倒计时?
有多种方法可以在Shell脚本中显示倒计时。

首先定义您的消息:

msg="Purging cache please wait..."

现在清除屏幕,并使用tput在第10行和第5列显示消息:

clear
tput cup 10 5
Next you need to display the message:
echo -n "$msg"

找出字符串的长度:

l=${#msg}

计算下一列:

l=$(( l+5 ))

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

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

这是一个完整的shell脚本:

#!/bin/bash
# Purpose: Purge urls from Cloudflare Cache
# Author:  {www.theitroad.local} under GPL v2.x+
# -------------------------------------------------------
# Set me first #
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版本

从这篇文章:

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" # 10 sec
countdown "00:00:30" # 30 sec
countdown "00:01:42" # 1 min 42 sec