title: Prevent SIGINT from interrupting current task while still passing information about SIGINT (and preserve the exit code)
body: <p>I have a quite long shell script and I'm trying to add signal handling to it.</p>
  
  <p>The main task of the script is to run various programs and then clean up their temporary files.</p>
  
  <p>I want to trap SIGINT.
  When the signal is caught, the script should wait for the current program to finish execution, then do the cleanup and exit.</p>
  
  <p>Here is an MCVE:</p>
  
  <pre><code>#!/bin/sh
  
  stop_this=0
  trap 'stop_this=1' 2
  
  while true ; do
      result="$(sleep 2 ; echo success)" # run some program
      echo "result: '$result'"
      echo "Cleaning up..." # clean up temporary files
      if [ $stop_this -ne 0 ] ; then
          echo 'OK, time to stop this.'
          break
      fi
  done
  
  exit 0
  </code></pre>
  
  <p>The expected result:</p>
  
  <pre><code>Cleaning up...
  result: 'success'
  Cleaning up...
  ^Cresult: 'success'
  Cleaning up...
  OK, time to stop this.
  </code></pre>
  
  <p>The actual result:</p>
  
  <pre><code>Cleaning up...
  result: 'success'
  Cleaning up...
  ^Cresult: ''
  Cleaning up...
  OK, time to stop this.
  </code></pre>
  
  <p>The problem is that the currently running instruction (<code>result="$(sleep 2 ; echo success)"</code> in this case) is interrupted.
  What can I do so it would behave more like I was set <code>trap '' 2</code>?</p>
  
  <p>I'm looking for either a POSIX solution or one that is supported by most of shell interpreters (BusyBox, dash, Cygwin...)</p>
  
  <p>I already saw answers for <a href="https://stackoverflow.com/questions/38800109/prevent-sigint-from-closing-child-process-in-bash-script">Prevent SIGINT from closing child process in bash script</a> but this isn't really working for me. All of these solutions require to modify each line which shouldn't be interrupted. My real script is quite long and much more complicated than the example. I would have to modify hundreds of lines.</p>