title: Shell script self-destruct and/or replace
body: <p>I have read that you can self destruct a script safely by adding <code>rm script.sh</code> anywhere in the script and the system will safely queue the file deletion until after the script is done running, but I have also read that it is <em>not</em> safe to modify a script within itself via <code>cp newscript.sh script.sh</code> because the buffer may start reading in <code>newscript.sh</code> before <code>script.sh</code> is done running.  However, is the following safe?</p>
  
  <p><strong>script.sh</strong></p>
  
  <pre><code>#!/bin/sh
  *some commands*
  replace.sh &amp;
  exit 0
  </code></pre>
  
  <p><strong>replace.sh</strong> (waits until <code>script.sh</code> finishes to do replacment)</p>
  
  <pre><code>#!/bin/sh
  while pidof -x script.sh
  do
      sleep 1
  done
  cp newscript.sh script.sh
  rm newscript.sh replace.sh
  exit 0
  </code></pre>
  
  <p><strong>Context</strong></p>
  
  <p>I'm using <code>rc.local</code> to run a one-time script at boot, but since it's only once, I want to restore <code>rc.local</code> with a backup I took.  I'm trying to avoid messing with <code>init.d</code> and <code>systemd</code>, etc.  I have tested whether I can successfully use a backgrounded process invoked by <code>rc.local</code> to test whether <code>rc.local</code> is still running and I can.</p>