Progressbar in bash to visualize the time to wait

In a bash script sometimes you need the user to wait some seconds for a background process to finish.

I usually use for example:

sleep 10

How can I add a kind of progressbar to the script, so the user knows how long to wait?

I installed the command bar but I don’t understand the manual.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

while true;do echo -n .;sleep 1;done &
sleep 10 # or do something else here
kill $!; trap 'kill $!' SIGTERM
echo done

this will start an infinite while loop that echos a spinner every second, executed in the background.

Instead of the sleep10 command run any command you want.

When that command finishes executing this will kill the last job running in the background (which is the infinite while loop)

source: https://stackoverflow.com/a/16348366/1069083

You can use various while loops instead, e.g. a spinner like this:

while :;do for s in / - \ |; do printf "r$s";sleep 1;done;done

Method 2

This should be enough to get you started:

#!/bin/bash

for i in {001..100}; do
    sleep 1
    printf "r $i"

done

Using the r escape sequence returns the line to the start without a newline. This allows you to update the output without having hundreds of lines of output. By using this base, you could find a way to slowly print out an arrow such as =>25% ==>50% ===>75% instead of simply printing a number out. You could do this in a very basic way by using if-then logic to print out a specific number of =’s depending on the size of the number.

Method 3

Here’s one using cursor movements that will rewrite the line in order to show a countdown:

c=5 # seconds to wait
REWRITE="e[25De[1Ae[K"
echo "Starting..."
while [ $c -gt 0 ]; do 
    c=$((c-1))
    sleep 1
    echo -e "${REWRITE}$c"
done
echo -e "${REWRITE}Done."

Method 4

In case you want to see the progress of a file-copy process, you can simply use

pv source_file > destination_file

or

rsync --progress source_file destination_file

instead of the cp command


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x