Prevent other terminals from running a script while another terminal is using it Prevent other terminals from running a script while another terminal is using it unix unix

Prevent other terminals from running a script while another terminal is using it


You can use the concept of a "lockfile." For example:

if [ -f ~/.mylock ]; then    echo "UNDER MAINTENANCE"    exit 1fitouch ~/.mylock# ... the rest of your coderm ~/.mylock

To get fancier/safer, you can "trap" the EXIT signal to remove it automatically at the end:

trap 'rm ~/.mylock' EXIT


Use flock and put this on top of your script:

if ! flock -xn /path/to/lockfile ; then    echo "script is already running."    echo "Aborting."    exit 1fi

Note: path/to/lockfile could be the path to your script. Doing so would avoid to create an extra file.


To avoid race conditions, you could use flock(1) along with alock file. There is one flock(1) implementationwhich claims to work on Linux, BSD, and OS X. I haven't seen oneexplicitly for Unix.
There is some interesting discussion here.

UPDATE:
I found a really clever way from Randal L. Schwartz here. I really like this one. It relies on having flock(1) and bash, and it uses the script itself as its own lockfile. Check this out:

/usr/local/bin/onlyOne is a script to obtain the lock

#!/bin/bashexec 200< $0if ! flock -n 200; then    echo "there can be only one"    exit 1fi

Then myscript uses onlyOne to obtain the lock (or not):

#!/bin/bashsource /usr/local/bin/onlyOne# The real work goes here.echo "${BASHPID} working"sleep 120