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

299 views Asked by At

I would like prevent other terminals from running a certain script whenever another terminal is running it however in bash but I'm not quite sure on how I would be able to go about in doing it. Any help or tip could be greatly appreciated!

In example: When that script is being run on another terminal, all other terminals would be unable to run that certain script as well. And display a message "UNDER MAINTENANCE".

3

There are 3 answers

1
John Zwinck On BEST ANSWER

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

if [ -f ~/.mylock ]; then
    echo "UNDER MAINTENANCE"
    exit 1
fi
touch ~/.mylock

# ... the rest of your code

rm ~/.mylock

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

trap 'rm ~/.mylock' EXIT
1
Erik Bennett On

To avoid race conditions, you could use flock(1) along with a lock file. There is one flock(1) implementation which claims to work on Linux, BSD, and OS X. I haven't seen one explicitly 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/bash
exec 200< $0
if ! flock -n 200; then
    echo "there can be only one"
    exit 1
fi

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

#!/bin/bash
source /usr/local/bin/onlyOne
# The real work goes here.
echo "${BASHPID} working"
sleep 120
0
hek2mgl On

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 1
fi

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