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?


4 Answers 4


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 ]
    echo hello
    touch /tmp/script.lock

Script B:

if [ -f /tmp/script.lock ]
    echo hello
    rm /tmp/script.lock
  • But be aware to touch /tmp/script.lock and rm /tmp/script.lock when the work is already done, to avoid the other script entering in an inconsistent state
    – Hobber
    Commented Nov 28, 2020 at 16:42

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.

[ ! -s "$CHECKFILE" ] && echo "$OTHERNAME" > "$CHECKFILE"
[ -s "$CHECKFILE" ] && grep -qwF "$MYNAME" && exit 1

# rest of script here


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. Commented Nov 5, 2015 at 20:51

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:

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .