Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

linux - How to: Progress bar in bash

I want to show a progress bar during a bash operation in a specific format something similar to the following:

[###########](40%)

after update it should become

[###############](50%)

and then similarly reach upto 100%

Is there any way to achieve this

I wrote the following bash program but i don't know how to show the percentage in this on same line:

#!/bin/bash
{
    echo -n "["
    for ((i = 0 ; i <= 100 ; i+=6)); do
        sleep 0.05
        echo -n "###"
    done
    echo -n "]"
    echo
}

Let's assume that a certain number of operations are being performed in a loop and after the completion of each operation, I want to report some progress. I don't want to install pv or any other utilities that does not come with default Ubuntu 12.04 installation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let's use echo -n '...' $' ' to print a carriage return:

for ((k = 0; k <= 10 ; k++))
do
    echo -n "[ "
    for ((i = 0 ; i <= k; i++)); do echo -n "###"; done
    for ((j = i ; j <= 10 ; j++)); do echo -n "   "; done
    v=$((k * 10))
    echo -n " ] "
    echo -n "$v %" $'
'
    sleep 0.05
done
echo

It makes the cursor move to the beginning of the line to keep printing.

Output is as follows, always in the same line:

[ ##################                ] 50 % 

.../...

[ ################################# ] 100 % 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...