1

I use the following script to check whether wget has finished downloading. To check for this, I'm looking for its PID, and when it is not found the computer shutdowns. This works fine for a single instance of wget, however, I'd like the script to look for all already running wget programs.

#!/bin/bash

while kill -0 $(pidof wget) 2> /dev/null; do
for i in '-' '/' '|' '\'
do
    echo -ne "\b$i"
    sleep 0.1
done
done
poweroff

EDIT: I'd would be great if the script would check if at least one instance of wget is running and only then check whether wget has finished and shutdown the computer.

Cœur
  • 37,241
  • 25
  • 195
  • 267
menteith
  • 596
  • 14
  • 51

3 Answers3

0

I don't think kill is a right Idea,

may be some thing on the lines like this

while [ 1 ] 
do
     live_wgets=0

     for pid in `ps -ef | grep wget| awk '{print $2}'` ;  # Adjust the grep
     do 
        live_wgets=$((live_wgets+1))
     done

     if test $live_wgets -eq 0; then # shutdown
         sudo poweroff; # or whatever that suits
     fi
     sleep 5; # wait for sometime 
done
asio_guy
  • 3,667
  • 2
  • 19
  • 35
0

You can adapt your script in the following way:

#!/bin/bash

spin[0]="-"
spin[1]="\\"
spin[2]="|"
spin[3]="/"

DOWNLOAD=`ps -ef | grep wget | grep -v grep`
while [ -n "$DOWNLOAD" ]; do
for i in "${spin[@]}"
do
    DOWNLOAD=`ps -ef | grep wget | grep -v grep`
    echo -ne "\b$i"
    sleep 0.1
done
done
sudo poweroff

However I would recommend using cron instead of an active waiting approach or even use wait

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

Allan
  • 12,117
  • 3
  • 27
  • 51
0

In addition to the other answers, you can satisfy your check for at least one wget pid by initially reading the result of pidof wget into an array, for example:

pids=($(pidof wget))
if ((${#pids[@]} > 0)); then 
    # do your loop
fi

This also brings up a way to routinely monitor the remaining pids as each wget operation completes, for example,

edit

npids=${#pids[@]}                           ## save original number of pids
while (( ${#pids[@]} -gt 0 )); do           ## while pids remain
    for ((i = 0; i < npids; i++)); do       ## loop, checking remaining pids
        kill -0 ${pids[i]} || pids[$i]=     ## if not unset in array
    done
    ## do your sleep and spin
done
poweroff

There are probably many more ways to do it. This is just one that came to mind.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85