0

I am attempting to write two scripts. But i run into problems when i try to prevent either one of them from running twice in a row. For example, i have script1 and script2. i want to be able to run script1 if and only if script2 was run since the last time i ran script1. any ideas?

1

In script A, look to see if a certain file exists, and if not, touch a file in the /tmp directory (eg: touch /tmp/script.lock) and run the code. Then in script B, check if the file exists. If the file exists, run the body of the script and then delete the file afterwards.

Script A:

if [ ! -f /tmp/script.lock ]
then    
    echo hello
    touch /tmp/script.lock
fi

Script B:

if [ -f /tmp/script.lock ]
then
    echo hello
    rm /tmp/script.lock
fi
1

Have each script check a certain file (e.g. /var/tmp/script1-2).

If the check file doesn't exist, write the other script's name into the file as early as possible, to prevent it running while this script is running.

If it exists and contains its own name, then exit. Otherwise run normally.

Just before exiting, each script should write its own name into the file.

CHECKFILE="/var/tmp/script1-2"
MYNAME='script1'
OTHERNAME='script2'
[ ! -s "$CHECKFILE" ] && echo "$OTHERNAME" > "$CHECKFILE"
[ -s "$CHECKFILE" ] && grep -qwF "$MYNAME" && exit 1

# rest of script here
.
.

echo "$MYNAME" > "$CHECKFILE"

The grep options are:

  • -q for quiet, produce no output
  • -w for matching whole words only
  • -F for matching fixed strings, not regular expressions.

Note: if both scripts are run at exactly the same time and $CHECKFILE doesn't exist yet, then they will both run. Whichever one finishes last (takes more time to run) will end up with its name written in $CHECKFILE. To prevent this, run echo script2 > /var/tmp/script1-2 before running either of them.

  • This allows a race condition. If you get each script to write the other script's name when that other script is allowed to run, you'll avoid the race. It would need starting off, of course. – roaima Nov 5 '15 at 20:51
0

One option could be to run the "date" command within script 1 and redirect this output to some file, say "file.txt" - and then script 2 can read this "file.txt" and do a "date" comparison between this date and the date at which script 2 was run? "Date" comparisons should be relatively easy to do - lots of examples on web (I believe). Food for thought.

Another option (depending on your requirement) is ofcourse adding "cron" job entries.

0

If you just want to know whether script2 has run before do this:

In script2 do anywhere:

touch .ran_already.

Now in script1 do:

if [ -f .ran_already ] then Here comes what the script does.. rm -f .ran_already else echo "script2 didn't run yet!" fi

This will serve you good, although its quick and dirty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.