如何在 Unix 中显示脚本执行的百分比进度?

如何在 Unix 中显示脚本执行的百分比进度?

假设您运行一些脚本,例如 perl 或 tcl。例如,$ ./script.sh; ./script.pl; source script.tcl。执行并返回提示需要一些时间。如何在执行的同时显示执行百分比?

您可以在下面找到一个示例 UI。它最后显示脚本的执行时间。

1% Completed the exectuion of script.pl
2% Completed the exectuion of script.pl
. . . .
100% Completed the the exectuion of script.pl

Ex: Execution time for script.pl is :50 Seconds

答案1

以下脚本显示:

  1. 当前项目(迭代)编号
  2. 滑动窗口平均速率(例如 10 次迭代的平均值)
  3. 总体平均率
  4. 到目前为止进度的百分比(如果灌溉次数已知)

输出:

317:  window: 3.76/s   overall: 3.28/s   progress: 31.7%

测试文件:

set test_file
# create a test file
for i in {1..1000} ;do echo $i; done >"$1"

剧本:

if="$1"             # the input file
lct=$(wc -l <"$if") # number of lines in input file
tot=${lct:-0}       # total number of itterations; If unknown, default is 0
                    #+  The total is know in this case. '$tot' is just a rough 
                    #+  example of how to suppress the progress %age output
beg=$(date +%s.%N)  # starting unix time.%N is nanoseconds (a GNU extension)
swx=10              # keep a sliding window of max 'n' itteratons (to average)
unset sw            # an array of the last '$swx' rates
for i in $(seq 1 $lct) ;do
    sw[$i]=$(date +%s.%N)  # sliding window start time
    # ================                   
      sleep .$RANDOM       #  ... process something here
    # ================
    now=$(date +%s.%N)     # current unix time
    if ((i<=swx)) ;then
        sw1=1              # first element of sliding window  
        sww=$i             # sliding window width (starts from 1)
    else
        sw1=$((i-swx+1))
        sww=$swx        
    fi
    bc=($(bc <<<"scale=2; $i/($now-$beg); $sww/($now-${sw[$sw1]})"))
    oavg=${bc[0]}                  # overall average rate
    swhz=${bc[1]}                  # sliding window rate
    ((i>swx)) && unset sw[$sw1-1]  # remove old entry from sliding window list
    ((tot==0)) && pc= || pc="progress: $(bc <<<"scale=1; x=($i*100)/$tot; if (x<1) print 0; x")%"
    msg="$i:  window: $swhz/s   overall: $oavg/s   $pc"
    printf "\r%"$((${#i}+1))"s=\r%s" "" "$msg"
done

相关内容