title: How do I synchronize (lock/unlock) access to a file in bash from multiple scripts?
body: <p>I'm writing scripts that will run in parallel and will get their input data from the same  file. These scripts will open the input file, read the first line, store it for further treatment and finally erase this read line from the input file.</p>
  
  <p>Now the problem is that multiple scripts accessing the file can lead to the situation where two scripts access the input file simultaneously and read the same line, which produces the unacceptable result of the line being processed twice.</p>
  
  <p>Now one solution is to write a lock file (<code>.lock_input</code>) before accessing the input file, and then erase it when releasing the input file, but this solution is not appealing in my case because sometimes NFS slows down network communication randomly and may not have reliable locking.</p>
  
  <p>Another solution is to put a process lock instead of writing a file, which means the first script to access the input file will launch a process called lock_input, and the other scripts will <code>ps -elf | grep lock_input</code>. If it is present on the process list they will wait. This may be faster than writing to the NFS but still not perfect solution ... </p>
  
  <p><strong>So my question is</strong>: Is there any bash command (or other script interpreter) or a service I can use that will behave like semaphore or mutex locks used for synchronization in thread programming?</p>
  
  <p>Thank you.</p>
  
  <p>Small rough example:</p>
  
  <p>Let's say we have input_file as following:</p>
  
  <pre>Monday
  Tuesday
  Wednesday
  Thursday
  Friday
  Saturday 
  Sunday</pre>
  
  <p>Treatment script : TrScript.sh</p>
  
  <pre><code>#!/bin/bash  
  NbLines=$(cat input_file | wc -l)  
  while [ ! $NbLines = 0 ]  
  do  
    FirstLine=$(head -1 input_file)  
    echo "Hello World today is $FirstLine"  
    RemainingLines=$(expr $NbLines - 1 )  
    tail -n $RemainingLines input_file &gt; tmp  
    mv tmp input_file  
    NbLines=$(cat input_file | wc -l)   
  done
  </code></pre>
  
  <p>Main script:</p>
  
  <pre><code>#! /bin/bash  
  ./TrScript.sh &amp;  
  ./TrScript.sh &amp;  
  ./TrScript.sh &amp;  
  wait
  </code></pre>
  
  <p>The result should be:</p>
  
  <pre>Hello World today is Monday  
  Hello World today is Tuesday  
  Hello World today is Wednesday  
  Hello World today is Thursday  
  Hello World today is Friday  
  Hello World today is Saturday  
  Hello World today is Sunday</pre>