2

I'm currently writing a Bash script. I want to download a file while printing text. For example, consider this script:

echo -e "---------------------------"
echo -e "Your file downloading..." 
echo -e "---------------------------"
wget example.com/1gbfile

In the second echo each . should be printed successively every second till the download finishes. If the number of . becomes three, like this: ..., it should be reset to only one . and continue the loop.

Erikli
  • 429

1 Answers1

4
Main script:

Create the following script as the source for your progress/bouncing bar (I called it bash-progress):

#!/bin/bash

Initial configuration variables

Set time interval for progress delay (in fraction of seconds)

time_delay=".2"

Set left and right brackets (1 character)

lb="["

lb="("

lb=" "

rb="]"

rb=")"

rb=" "

Function to show bouncing bar while running command in the background

show_bouncer() {

If no argument is given, then this is run on the last command - else provide PID

if [[ -z $1 ]] then PID=$! else PID=$1 fi ii=0

Define bouncer array (3 characters)

bo=('. ' '.. ' '...' ' ..' ' .' ' ..' '...' '.. ')

bo=('⠄ ' '⠂⠄ ' '⠁⠂⠄' '⠂⠂⠂' '⠄⠂⠁' ' ⠄⠂' ' ⠄' ' ')

bo=('⡇ ' '⣿ ' '⣿⡇ ' '⢸⣿ ' ' ⣿⡇' ' ⢸⡇' ' ⡇' ' ')

True while the original command is running

while [[ -d "/proc/$PID" ]] do ch="${bo[(ii++)%${#bo[@]}]}" printf "%b" " ${lb}${ch}${rb}" sleep "$time_delay" # Adjust backspaces to bouncer length + 3 printf "\b\b\b\b\b\b" done }

The script can work in 2 ways: Either by using the PID of the last command run, or with a given PID. The most common use is with the last command.

Using it:

So you simply create your other script like this:

#!/bin/bash

Include Bash progress bars - or include the entire source in your script.

source "./bash-progress"

your_command_here & show_bouncer

It's important to run the command in the background, since it then moves on immediately to show the bouncer.

You can easily test it with a sleep command:

#!/bin/bash

Include Bash progress bars - or include the entire source in your script.

source "./bash-progress"

sleep 5 & show_bouncer

Bonus info:

To use with a PID other than the last one, you can use pgrep (-n for newest and -x for exact match) to find the latest instance of the process like this:

#!/bin/bash

Include Bash progress bars - or include the entire source in your script.

source "./bash-progress"

your_command & do_something_else do_anything_meanwhile show_bouncer $(pgrep -nx "your_command")

Artur Meinild
  • 31,035