6

我正在编写一个小脚本来处理文件夹。运行时间很长,所以我想添加一个进度条。

这是迭代:

for file in */
do 
    #processing here, dummy code
    sleep 1
done

拥有一个计数器并知道文件夹的数量将是一个解决方案。但我正在寻找更通用和更短的解决方案......

我希望有人会有一个想法。感谢您的关注,

朱利安

编辑 :

我得到了这个解决方案,它可以满足我的需求,而且非常图形化:

#!/bin/bash
n_item=$(find /* -maxdepth 0 | wc -l)
i=0
for file in /*
do
    sleep 1 #process file
    i=$((i+1))
    echo $((100 * i / n_item)) | dialog --gauge "Processing $n_item folders, the current is $file..." 10 70 0
done

但是,我会保留 fedorqui 的解决方案,它不会占用所有屏幕。

非常感谢您的宝贵时间

4

3 回答 3

6

根据我们在如何打印到同一行,覆盖上一行?我得到了这个结果:

#!/bin/bash

res=$(find /* -maxdepth 0 | wc -l)
echo "found $res results"
i=1

for file in /*
do
    echo -n "["
    for ((j=0; j<i; j++)) ; do echo -n ' '; done
    echo -n '=>'
    for ((j=i; j<$res; j++)) ; do echo -n ' '; done
    echo -n "] $i / $res $file" $'\r'
    ((i++))
    sleep 1
done

例子

$ ./a
found 26 results
[  =>                        ] 2 / 26 /boot 
[                =>          ] 16 / 26 /root
于 2013-09-27T08:54:52.593 回答
4

基于 fedorqui 的惊人解决方案,我制作了一个适用于任何循环的函数。

function redraw_progress_bar { # int barsize, int base, int i, int top
    local barsize=$1
    local base=$2
    local current=$3
    local top=$4        
    local j=0 
    local progress=$(( ($barsize * ( $current - $base )) / ($top - $base ) )) 
    echo -n "["
    for ((j=0; j < $progress; j++)) ; do echo -n '='; done
    echo -n '=>'
    for ((j=$progress; j < $barsize ; j++)) ; do echo -n ' '; done
    echo -n "] $(( $current )) / $top " $'\r'
}

所以你可以很容易地做像这样的循环

for (( i=4; i<=20 ; i+=2 ))
do
    redraw_progress_bar 50 4 $i 20
    $something $i
done
echo $'\n'
于 2013-12-01T11:34:55.117 回答
3

如果您想要图形进度条 (GTK+),请查看 zenity :

#!/bin/bash
(
    for i in {0..5}
    do
        echo $((i*25))
        echo "#Processing $((i+1))/5"
        sleep 1
    done
) | zenity --progress --width=400 --title="Please wait" --auto-close
于 2013-12-02T23:31:47.597 回答