linuxbashshellbinzenity

How to stop bash script after I click cancel on zenity progress window


I'm writting a script using bash script, in this code I have a process that runs together with a zenity progress bar. What is happening is that when I run it, and try to cancel the operation, it will keep running until I clic ctrl+c on the linux terminal, that is meant for cancelling the operation. Since I'm doing this for users that aren't programmers, this can't be the way to stop it.

This is the line I'm talking about:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH sOutputFile="$DESTINO.pdf" "$FILE" | zenity --progress --title="Processando" --auto-close --width=220 --text="Comprimindo PDF" --pulsate --percentage=0 

I thought that I had the answer to solve this problem, because I used it in the other zenity windows like this one:

zenity --width=600 --height=300 --text-info --title="Test" --filename=/tmp/original.txt --editable > /tmp/changed.txt
case $? in
    1)
        exit
    ;;
esac

It works just fine, when I click cancel it stop the script, but when I tried to use it in the progress bar that runs with the gs command, it didn't work, the zenity window closed, but the script kept running. This is how I tried solving it:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile="$DESTINO.pdf" "$FILE" | zenity --progress --title="Processando" --auto-close --width=220 --text="Comprimindo PDF" --pulsate --percentage=0 
case $? in
    1)
        exit
        ;;
esac

Anyone has ever had this problem? How can I solve it? Thanks.


Solution

  • Here's a suggestion (backslashes used for readability) :

    #! /bin/sh
    
    hup_handler()
      {
      kill -s KILL "$!"
      }
    
    trap hup_handler HUP
    
    gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook \
       -dNOPAUSE -dQUIET -dBATCH -sOutputFile="$DESTINO.pdf" "$FILE"   \
    | zenity --progress --title="Processando" --auto-close --auto-kill \
             --width=220 --text="Comprimindo PDF" --pulsate --percentage=0 &
    wait
    
    echo 'end of script'
    

    Apparently zenity --progress --auto-kill sends a HANGUP signal to the parent process when the "cancel" button is pressed. For some reason beyond my knowledge, that signal is processed only when the pipeline has completed unless you place it in the background with &.

    If you want to delete the file when the user clicks on the "cancel" button, you could add rm -f "$DESTINO.pdf" in the hup_handler function.

    Hope that helps.