I wrote a bash script to automate a very long process. It works good.
However, if the user should control-c or rerun due to a ssh disconnect I find that there is a remnant of the previous execution still running if I: ps -ef|grep myprogram.
I believe the problem is in this snippet of code in which I background each step so I can show the user a spinning progress bar:
<snippet begin>
function progress {
SPIN='-\|/'
# Run the base 64 code in the background
echo $THECOMMAND | base64 -d|bash &
pid=$! # Process Id of the previous running command
i=0
while kill -0 $pid 2>/dev/null
do
i=$(( (i+1) %4 ))
# Print the spinning icon so the user knows the command is running
printf "\r$COMMAND:${SPIN:$i:1}"
sleep .2
done
printf "\r"
}
<snippet end>
Question: What code can I add to my script that will detect a failure or control-c and kill the background process?
Additional info: I run the script from a wrapper and I run this in a screen session.
myprogram.sh $1 > >(tee -a /var/tmp/myprogram_install$DATE.log) 2> >(tee -a /var/tmp/myprogram_install$DATE.log >&
trapcommand