Find out if a script has ended or still running

I have a script which will run for sometime, i want to monitor it's progress by sending out a mail by runing a infinite loop from command line

for eg. this is the script

$cat script1.sh
#!/usr/bin/ksh
i=0
while [ $i -lt 20 ]
do
  sleep 2
  echo $i hi
  i=`expr $i + 1`
done > testprog.out

###################################

this is how the monitoring prog will run from command line

while 1
do
 
  if [ **script1 has finished ]
  then
    mailx -s "Script Finished" < echo " "
    exit 0
  else
    mailx -s "test out" abc@def.com < testprog.out
  fi
done

###################################
However, I am not able to figure out how to do the tasks marked as **
i.e how to find out script1 is still runing or has finished ?

Check for the process is running for that script..

Depending on your OS, you may be able to check the result of ps -fC script1.sh or ps -ef | grep cript1.sh .

Alternatively, get script1.sh to write its PID to a file somewhere and check for that.

while [ 1 ]
do

processes_running=`ps -fu <username>|grep -e "$JOBNAME" |grep -v grep|wc -l`
if [ $processes_running -ge 1 ]
then

<whatever you want do if jobname is running>

else

<whatever you want do if jobname is not running>

fi

done
1 Like

Depending on what you're trying to do, this could be a good use for lock files. There's a bunch of different ways you could do it. But based on the simplicity of your example, the easiest way would probably be to first alter the first script as such:

#!/usr/bin/ksh
echo "??" > /var/lock/scriptname.lock #echo the pid of this script into a "lock" file
i=0
while [ $i -lt 20 ]
do
  sleep 2
  echo $i hi
  i=`expr $i + 1`
done > testprog.out
rm /var/lock/scriptname.lock #Remove the lock file when script is done. 

Then, monitoring would be as simple as (not formatted because I'm obviously not testing this, just throwing out ideas)

until [[ ! -f /var/lock/scriptname.lock ]];do echo "nope";sleep 2;done;<whatever you want to do when the script is over>

which is really just saying until the lock file doesn't exist, sleep for 2 seconds and then check again. Once it doesn't exist anymore, kill the loop and do the next command...which is whatever you want.

1 Like

Thanks everyone, I got this now

Special thanks to DeCoTwc for this very useful post