2

I am currently trying to figure out how to make bash draw a series of dots across the screen (kind of like a progress indicator) until a command finishes executing. For example, say I want to draw dots for a wget download:

wget -s http://url.tar.gz
until "above command has finished executing"; do
    echo -n "."
    sleep 0.05s
done

Can I use "$!" or "$?" to help solve this?

Thank you for the help!

  • @Squirrel He doesn't want to get the exit code, he wants to detect whether the background process is still running or not. – Barmar Feb 06 '15 at 02:09
  • Why don't you just use the built-in progress indicator of `wget`? – Barmar Feb 06 '15 at 02:10
  • I flagged it because the question body (not the title) actually asks this exact thing, and the top answer actually has code that shows how to do it. – Squirrel Feb 06 '15 at 02:10
  • 1
    @Barmar I didn't want to use wget's built in progress bar because it would be easier for me to replicate the dots across different executable files that might not have progress indicators of any kind. – Duncan G. Britton Feb 06 '15 at 02:19

2 Answers2

5

This will print dots until wget completes:

while sleep 0.1; do printf "."; done &
wget -q http://url.tar.gz
kill $!
echo "Finished"

wget has its own progress indicator. The above uses -q to turn that off.

$! expands to the PID of the last process executed in the background which, in this case, is the while loop that prints the dots. Thus, kill $! stops the loop, ending the printing of dots.

John1024
  • 109,961
  • 14
  • 137
  • 171
2

Thanks to Squirrel, I was able to solve this. He pointed me to a thread that I had duplicated shell - get exit code of background process. By adding the following to my script, I was able to get it working how I had hoped:

wget -q http://url.example.com.tar.bz2 &
wget_pid=$!

while [ -d /proc/$wget_pid ]; do
    echo -n "."
    sleep 0.01s
done
Community
  • 1
  • 1
  • As coded the `while` loop is not entered until `wget` has completed. In order for the `while` loop to be entered as `wget` is retrieving the file you need to append an ampersand `&` to the `wget` command, e.g.: `wget -q http://url.example.com.tar.bz2 &` – user3439894 Feb 06 '15 at 02:53
  • I must have forgotten to add that "&." Thanks for pointing that out. – Duncan G. Britton Feb 12 '15 at 21:51