1

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 >&
1
  • 4
    Look up the trap command
    – 123
    Nov 2, 2017 at 15:32

1 Answer 1

5

One way to do it:

quit=n
trap 'quit=y' INT

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
   if [ x"$quit" = xy ]; then
    kill $pid
    break
   fi
   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"
}
2
  • Thanks. Pleading ignorance here. Can you help me understand how this works? I assume INT is an interrupt?? How does x"$quit" = xy get evaluated?
    – Marinaio
    Nov 2, 2017 at 18:25
  • 1
    No. INT is the SIGINT signal, and [ x"$quit" = xy ] is the test $quit == y. When you press Ctrl-C a SIGINT signal is delivered to your script, and quit is set to y because of trap. You can then test for the value of quit in your function. Nov 2, 2017 at 19:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .