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?
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.
if [ ! -f /tmp/script.lock ] then echo hello touch /tmp/script.lock fi
if [ -f /tmp/script.lock ] then echo hello rm /tmp/script.lock fi
Have each script check a certain file (e.g.
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"
grep options are:
-qfor quiet, produce no output
-wfor matching whole words only
-Ffor 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.
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.
If you just want to know whether script2 has run before do this:
In script2 do anywhere:
Now in script1 do:
if [ -f .ran_already ]
Here comes what the script does..
rm -f .ran_already
echo "script2 didn't run yet!"
This will serve you good, although its quick and dirty.