1

I am running a shell script in server with command line arguments as follows.

./xyz.sh DD 10 20 

I want to write some check code inside the script that it will detect if same script is running in the server. If the same is running then it won't run , otherwise it will run. N.B. the command line arguments may differ for different run of the same script.

Any help on this is welcome.

user3627319
  • 395
  • 3
  • 10
  • 19

2 Answers2

2

You have various ways of checking if a program is running.

Checking for a running program with the same name

pidof xyz

This will print the pids of every program named "xyz", and return with exit code 0 if a pid was found and 1 if not (so if you just want to know if the program is running, you just have to check the exit code of that command).

If you don't have pidof:

ps aux | grep xyz.sh | grep -v grep

And check if the output is empty or not.

A more reliable solution

If you want something a bit more sophisticated (that will check if this script is running, and not just something with the same name), the solution is usually to create a pid file:

At the beginning of the script, check if the file /var/run/xyz.pid exists. If it exists, then the program is already running. If not, then create it and continue your normal execution. At the end of the normal execution of the script, remove the file.

You may write the pid of the script as you create the xyz.pid file. That way, if the user wants to stop the running script without killing it themselves, they can call the script again with an option like, for example, --stop. Then your script can read the .pid file and kill it properly (by sending a signal asking it to shut down gracefully for example).

This is the way a lot of services (some http servers for example) work.

Dettorer
  • 1,247
  • 1
  • 8
  • 26
0

You can also try implementing a lock file. First create a file when the shell executes. Before creating the file check if it exists. If it does then skip the process if not continue.

DRTauli
  • 731
  • 1
  • 8
  • 25
  • Hi DRTauli, I want a check inside the script it self.. So any sugestion on this? – user3627319 Dec 08 '14 at 09:41
  • use this [link](http://stackoverflow.com/questions/16828035/linux-command-to-check-if-a-shell-script-is-running-or-not) to get your answer: http://stackoverflow.com/questions/16828035/linux-command-to-check-if-a-shell-script-is-running-or-not – Shantanu Dec 08 '14 at 10:34