Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 997
maihabunash Avatar asked Mar 17 '23 19:03

maihabunash


1 Answers

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.

like image 90
MarcoS Avatar answered Mar 26 '23 02:03

MarcoS