title: How to make file lock with bash
body: <p>I have a task to rsync a dir from remote server</p>
  
  <pre><code>rsync -av root@s0.foo.com:/srv/data/ /srv/data/ 
  </code></pre>
  
  <p>To make it run regularly and avoid Script "reEnter" issue, I create a file lock "in_progress" with rsync progress's pid, which indicate whether the program is still running. <br/><br/></p>
  
  <pre><code>lock(){
      echo $1 &gt; in_progress
  }
  </code></pre>
  
  <p>Using this function to judge whether the rsync progress is still running:</p>
  
  <pre><code>is_running(){
     pid=$(cat in_progress)
     return ps aux | awk '{print $2}' | grep $pid
  }
  </code></pre>
  
  <p>I can get the pid to pass to function <code>lock</code> with this</p>
  
  <pre><code>$!
  </code></pre>
  
  <p>I had to put the rsync progress background to get the pid of rsync, so I get this</p>
  
  <pre><code>rsync -av root@s0.foo.com:/srv/data/ /srv/data/ &amp; 
  lock $!
  </code></pre>
  
  <p>but when rsync progress is done, I should rm the lock file<br/>
  I tried this</p>
  
  <pre><code>rsync -av root@s0.foo.com:/srv/data/ /srv/data/ &amp;&amp; rmLock &amp; 
  lock $!
  </code></pre>
  
  <p>... then it seems the pid I got is not the pid of rsync progress :-(</p>