How to lock a file through UNIX KSH shell script?

I wrote two shell scripts in UNIX that renames the same file and scheduled them at the same time.

The following are the steps that I followed:-

  1. I wrote 2 scripts named s1.sh and s2.sh, both trying to add �exec_� prefix to the name of the files present in a folder i which already don't start with �exec_�. When any script performs the renaming operation, then that step is noted in their respective log file.
    For e.g., if script s1.sh tries to rename f1 file, then the message �f1 has been renamed to exec_f1� along with the time of the action is written in log1 file.
  2. I scheduled both the scripts at the same time with the following 2 commands :-
    a. at -f s1.sh 5:36 PM
    b. at -f s2.sh 5:36 PM
    The output that we saw was that in both log1 and log2 files same actions were logged at the same time. So, both the scripts accessed the same file at the same time.

Now what I want to do is if suppose s1.sh has already accessed a file called f1 then s2.sh will not access it and will take the next file say f2.

Can anyone please tell me how to do that?

Why did you schedule both scripts to run at the exact same time? Is there a reason for that?

If the script(s) only operate on files NOT starting "exec" then once the rename is done, the second script won't find those files.

What command(s) are you using to rename the file(s)? mv?

Please post the script.

I assume this is a test case/prototype for something more complicated? Exactly what do you need to achieve? It's simpler to stop a duplicate script from running rather than trying to lock files individually.

If the scripts are using a for ls/find loop then they may well get the same (or very similar, depending on exact scheduling) list of files to operate on, since the renames (or most of them) won't have happened yet.

@CarloM......yes, but, even if both scripts identify the same list of files to operate on only one script can actually do the renaming and the second script should throw an error that the file has disappeared.

If they are both doing the same thing, then are they really two scripts? If this is a common function that they would both do, then perhaps it would be better to break that out into a separate function and organise your scheduler a little differently.

If you have Job1 & Job2 currently running in parallel, consider having Job0 to do the common renaming work and then make the remainder of Job1 & Job2 as a dependency on Job0 completing. I suppose it depends on your scheduler.

If it's cron, then it's a little tricky. Commercial schedulers should provide this job dependency control. if you are stuck with cron then consider using some sort of a file to flag that Job0 has completed and have Job1 & Job2 wait for it to appear.

As hicksd8 requests, Please post the script.
As CarloM asks though, what do you really need to achieve?

Robin