Timing a running process in bash script - having my cake and eating it too :-)
by taylorkh from LinuxQuestions.org on (#4WH4Y)
I need to call a process from a script. It may or may not complete in a reasonable amount of time. I would like to be able to "start the clock" on the process and then, if the process completes I would examine the return code and move on. If I reach my timeout limit I would take other actions. Here is a test script which I have written in an attempt to figure this outCode:#!/bin/bash
function my_function {
declare -i j=0
while [ $j -lt 5 ]
do
echo hello
j=$j+1
done
sleep 5
echo
return 27
}
SECONDS=0
running=0
elapsedseconds=0
while [ $elapsedseconds -lt 10 ]
do
if [ $running -eq 0 ]
then
running=1
my_function
else
sleep 1
fi
elapsedseconds=$SECONDS
echo $elapsedseconds
done
echo "time is up!"
echo $?In this case "my_function" will launch and control will NOT return to the script until my_function completes. If I change the script to execute my_function& control returns to the calling script but I loose the return code from my_function. With my_function& and setting the sleep in the function to 15 illustrates part of what I wish to achieve.
In my actual script my_function will call an external script and I could, using my typical big hammer programming approach, simply wait for a reasonable time and the check to see if the process has completed satisfactorily. If not I will kill the process with my big hammer and move on to take remedial action. That would get the job done but it is rather crude. Any suggestions?
TIA,
Ken
p.s. Bonus question :D
Why do I have to declare j as an integer lest I get an error "integer expression expected" while I do NOT have to declare elapsedseconds? :scratch:


function my_function {
declare -i j=0
while [ $j -lt 5 ]
do
echo hello
j=$j+1
done
sleep 5
echo
return 27
}
SECONDS=0
running=0
elapsedseconds=0
while [ $elapsedseconds -lt 10 ]
do
if [ $running -eq 0 ]
then
running=1
my_function
else
sleep 1
fi
elapsedseconds=$SECONDS
echo $elapsedseconds
done
echo "time is up!"
echo $?In this case "my_function" will launch and control will NOT return to the script until my_function completes. If I change the script to execute my_function& control returns to the calling script but I loose the return code from my_function. With my_function& and setting the sleep in the function to 15 illustrates part of what I wish to achieve.
In my actual script my_function will call an external script and I could, using my typical big hammer programming approach, simply wait for a reasonable time and the check to see if the process has completed satisfactorily. If not I will kill the process with my big hammer and move on to take remedial action. That would get the job done but it is rather crude. Any suggestions?
TIA,
Ken
p.s. Bonus question :D
Why do I have to declare j as an integer lest I get an error "integer expression expected" while I do NOT have to declare elapsedseconds? :scratch: