3

How can I lock a file using Linux (CygWin) shell scripting?
I need to detect it later in the code of another shell scripting.
Reason for doing this: I have two Linux (CygWin) shell scripts (named A and B), and would like to use file locking to make the first (A) to be able detect if the second (B) is running. Even when there are other methods to detect if a program is running, I would like to learn the filelocking method, since it could some day have advantages.

2
  • Possible duplicate of Quick-and-dirty way to ensure only one instance of a shell script is running at a time Commented Jan 24, 2018 at 21:39
  • I should point out that Linux IS NOT Cygwin or, visa versa. This is the reason people push the term "GNU/Linux" to refer to what people usually call the "Linux" OS. The better term to use is a *NIX because almost ever bit of this applies to any UNIX, including Mac OX (which is a UNIX), although flock is from util-linux, which is a Linux project... Somehow I don't feel that I've made things clearer here :( Commented Jan 3, 2020 at 3:14

1 Answer 1

3

Use flock for both things: locking a file during the execution of the script B and checking the lock status from the script.
When launching script B:

flock /tmp/lockfile.lck ScriptB.sh

Inside script A, to detect the lock:

flock -n /tmp/lockfile.lck echo "Script B is not running" || echo "Script B is running right now"

The '-n' option makes flockto "not wait" for the releasing (the default action) of the lock file. Thus, that would be another way of using flock, if waiting is what you desire.

Sign up to request clarification or add additional context in comments.

2 Comments

flock looks perfect... but I can't seem to find it in cygwin or cygwin64, which this question is tagged. Am I missing something?
@WernerCD , It is included in the util-linux package.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.