5

I want to add a progress bar in my bash script that show the "." character as progress , and process ended after MAX 180 second

in the bash script I use curl command , so curl give the results after sometime but not greater then 180 sec

something like that

|.                                           after 2 sec
|...........                                 after 60 sec
|...................                         after 100 sec
|..........................                  after 150 sec
|................................|           after 180 sec 

final example

|................................|       after 180 sec 

or

|....|                                   after 30 sec 
1

2 Answers 2

13

This is rather simple to do in just plain Bash:

#!/bin/bash
# progress bar function
prog() {
    local w=80 p=$1;  shift
    # create a string of spaces, then change them to dots
    printf -v dots "%*s" "$(( $p*$w/100 ))" ""; dots=${dots// /.};
    # print those dots on a fixed-width space plus the percentage etc. 
    printf "\r\e[K|%-*s| %3d %% %s" "$w" "$dots" "$p" "$*"; 
}
# test loop
for x in {1..100} ; do
    prog "$x" still working...
    sleep .1   # do some work here
done ; echo

The first argument to prog is the percentage, any others are printed after the progress bar. The variable w in the function controls the width of the bar. Print a newline after you're done, the function doesn't print one.


Another possibility would be to use the pv tool. It's meant for measuring the throughput of a pipeline, but we can create one for it:

for x in {1..100} ; do
    sleep .1    # do some work here
    printf .
done | pv -pt -i0.2 -s100 -w 80 > /dev/null

Here, -pt enables the progress bar and the timer, -s 100 sets the total output size, and whatever we print inside the function counts against that size.

1

In general, you can implement this by overwriting a line. Use \r to go back to the beginning of the line without writing \n to the terminal.

Write \n when you're done to advance the line.

Use echo -ne to:

  • not print \n and
  • to recognize escape sequences like \r.

Here's a demo:

echo -ne '...                     (33%)\r'
sleep 1
echo -ne '......                  (66%)\r'
sleep 1
echo -ne '..........              (100%)\r'
echo -ne '\n'

EDIT: Now, cURL comes with a progress bar: --progress-bar, is that not what you want ?

taken from answer to https://stackoverflow.com/questions/238073/how-to-add-a-progress-bar-to-a-shell-script

Found that with Google, first answer, with the following search terms: "bash progress bar"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.