Sometimes we need limit the access to some system resources or files. We want to be sure that the only one process to have an access to them in the same time. This short article explains how to use exclusive locks in shell scripts.
Assume we have a shell script (‘writer.sh‘) which writes an output file (‘output.txt‘). It writes the file line by line with one second delay between each line.
$ cat ./writer.sh #!/bin/bash outfile="./output.txt" echo -n "" > $outfile for i in {1..20} do echo "Line $i" >> $outfile sleep 1 done
We have a second script too – ‘reader.sh‘ which simply reads ‘output.txt‘ file.
$ cat ./reader.sh #!/bin/bash outfile="./output.txt" cat $outfile
What will happen if we start writer.sh and then (after 3-4 seconds) reader.sh script? Reading script will read partially written output file and we’ll see something like this:
$ ./reader.sh Line 1 Line 2 Line 3 Line 4
How to avoid this? Use flock command.
Start writer.sh with lock.
$ flock /var/lock/writer.lock ./writer.sh
where /var/lock/writer.lock is a lock file.
Then after several seconds start reader.sh with the same lock.
$ flock /var/lock/writer.lock ./reader.sh
Second command will wait until writer.sh script ends (and releases lock). After that reader.sh will display whole output file.
Flock command also has an another interesting option -n or –nonblock. Using it causes immediately exit from flock process when lock cannot be acquired.