3

We are looking into building a logcheck script that will tail a given log file and email when the given arguments are found. I am having trouble accurately determining if another version of this script is running with at least one of the same arguments against the same file. Script can take the following:

logcheck -i <filename(s)> <searchCriterion> <optionalEmailAddresses>

I have tried to use ps aux with a series of grep, sed, and cut, but it always ends up being more code than the script itself and seldom works very efficiently. Is there an efficient way to tell if another version of this script is running with the same filename and search criteria? A few examples of input:

EX1 .\logcheck -i file1,file2,file3 "foo string 0123" email@address.com
EX2 .\logcheck -s file1 Hello,World,Foo
EX3 .\logcheck -i file3 foo email@address1.com,email@address2.com

In this case 3 should not run because 1 is already running with parameters file3 and foo.

jww
  • 97,681
  • 90
  • 411
  • 885
  • 3
    Create a hash from the arguments to form a unique filename, then attempt to exclusively create the file? – jxh Nov 14 '17 at 00:08
  • 1
    Maybe related, [How to make sure only one instance of a bash script runs?](https://unix.stackexchange.com/q/48505/56041), [What is the best way to ensure only one instance of a Bash script is running?](https://stackoverflow.com/q/1715137/608639), [Continue script if only one instance is running?](https://stackoverflow.com/q/2530114/608639), [Quick-and-dirty way to ensure only one instance of a shell script is running at a time](https://stackoverflow.com/q/185451/608639), etc. – jww Nov 14 '17 at 00:24

1 Answers1

0

There are many solutions for your problem, I would recommend creating a lock file, with the following format:

arg1Ex1 PID#(Ex1)
arg2Ex1 PID#(Ex1)
arg3Ex1 PID#(Ex1)
arg4Ex1 PID#(Ex1)
arg1Ex2 PID#(Ex2)
arg2Ex2 PID#(Ex2)
arg3Ex2 PID#(Ex2)
arg4Ex2 PID#(Ex2)

when your script starts:

  • It will search in the file for all the arguments it has received (awk command or grep)
  • If one of the arguments is present in the list, fetch the process PID (awk 'print $2' for example) to check if it is still running (ps) (double check for concurrency and in case of process ended abnormally previously garbage might remain inside the file)
  • If the PID is still there, the script will not run
  • Else append the arguments to the lock file with the current process PID and run the script.
  • At the end, of the execution you remove the lines that contains the arguments that have been used by the script, or remove all lines with its PID.
Allan
  • 12,117
  • 3
  • 27
  • 51
  • Thanks for the quick response. Our plan was to run this as a cron job. Would it not be possible for another process to take that same PID and cause false positives over time given there is no garbage collection? – Tyler Schimke Nov 15 '17 at 22:41