1

I need to be able to call this:

watch -n1 cat /proc/mdstat

from bash.

For raid creating watching (after mdadm --create etc.), and then kill it then building process will end.

#!/bin/bash
#PID=$!
while
progress=$(cat /proc/mdstat |grep -oE 'recovery = ? [0-9]*')
do
    watch -n1 cat /proc/mdstat
    PID=$(pidof watch)
    echo "$PID" >> /mnt/pid
    if (("$progress" >= "100"))
        then
            break
            kill -9 $PID
    fi
done
echo "done" 

But I can not figure out how to kill watch out from bash. I tried PID=$! and PID=$$, pidof watch at the cycle and out of him, but can't assign correct PID to my variable to make kill -9 $PID.

tripleee
  • 175,061
  • 34
  • 275
  • 318
gek
  • 524
  • 6
  • 18
  • 2
    As an aside, you should basically never use `kill -9`. In normal circumstances, just `kill` should suffice. – tripleee Oct 03 '14 at 11:49
  • In this particular piece of code, the `break` causes the script to exit the loop, so your `kill` never gets executed. Switch the order of those two statements. – tripleee Oct 03 '14 at 11:50
  • Note that the watch command is run in the foreground. The script never reaches past the first execution of watch. – nos Oct 03 '14 at 11:54

1 Answers1

2

It sounds like you'll need to have watch running until progress reaches 100 ?

watch  -n1 cat /proc/mdstat &
WATCHPID=$!
while
progress=$(cat /proc/mdstat |grep -oE 'recovery = ? [0-9]*')
do

if (("$progress" >= "100"))
    then
        break

fi
sleep 1
done

kill $WATCHPID

echo "done" 
nos
  • 223,662
  • 58
  • 417
  • 506
  • great! i just can't understand how did you >watch -n1 cat /proc/mdstat **&** does not going to background? i tried it but couldn't take watch from background – gek Oct 03 '14 at 13:12
  • @gek I don't really understand what you're asking. The '&' makes the command go to the background. Your code doesn't have an '&'. – nos Oct 03 '14 at 13:56