0

I have a perl script runs in cron and if the script fails to run it leaves behind a lock file to prevent the script to run again.

I'm trying to run a bash script that checks if the process is running and checks to see if a lock file is left behind

if processes is running and lock file exists exit 0;

if process is not running and lock file exists rm lockfile. exit 0;

if process does not exist and lock file is 'not present' exit 0;

I've been checking if the process exists running ps ax |grep -v grep |grep process.pl

I'm looking for the conditionals in bash that I should be running here.

Thanks

elzwhere
  • 869
  • 1
  • 6
  • 13

4 Answers4

2

-e for "file exists":

$ if [ -e /etc/passwd ]; then echo "passwords" ; else echo "no passwords" ; fi
passwords

-n for "length of string is zero" (useful for your pidof(1) command).

$ F=$(pidof firefox-bin) ; if [ -n "$F" ]; then echo "browser" ; else echo "boring" ; fi
browser
$ F=$(pidof chrome) ; if [ -n "$F" ]; then echo "browser" ; else echo "boring" ; fi
boring

(I have firefox running, but not chrome.)

sarnold
  • 102,305
  • 22
  • 181
  • 238
1

The process.pl should write its process id into the lockfile, wihch is a common pattern. Then you can write the following code:

if [ -f "$lockfile" ]; then
  pid=$(cat "$lockfile")
  if kill -0 "$pid"; then
    : "running normally"
  else
    : "terminated somehow"
    rm -f "$lockfile"
  fi
fi
Roland Illig
  • 40,703
  • 10
  • 88
  • 121
0

Check this question for some techniques to make sure only 1 copy of script runs, in bash.

Community
  • 1
  • 1
0
pgrep -f process.pl || { [ -f lock.file ] && rm lock.file; } 
glenn jackman
  • 238,783
  • 38
  • 220
  • 352