Shell scripts and how to avoid running the same script at the same time on a Linux machine

bash, ksh, linux, shell

Solution

A common solution for your problem on *nix systems is to check for a lock file existence. Usually lock file contains current process PID. This is an example ksh script:

#!/bin/ksh

pid="/var/run/get_hosts.pid"
trap "rm -f $pid" SIGSEGV
trap "rm -f $pid" SIGINT

if [ -e $pid ]; then
    exit # pid file exists, another instance is running, so now we politely exit
else
    echo $$ > $pid # pid file doesn't exit, create one and go on
fi

# your normal workflow here...

rm -f $pid # remove pid file just before exiting
exit

UPDATE: Answering to OP comment, I add handling program interruptions and segfaults with `trap` command.

Problem

I have Linux centralize server – Linux 5.X. In some cases on my Linux server the get_hosts.ksh script could be run from some other different hosts. For example get_hosts.ksh could run on my Linux machine three or more times at the same time. My question: - How to avoid running multiple instances of process/script?

Original source

Related problems