Reputation: 4590
I am very new to bash scripting. I have read man page for flock but still I am not very clear how it works here. I'd appreciate if anyone could explain it for me.
if [ "$passfile" != "/etc/passwd" ]; then
(
flock -e 200
echo "$theUsername:$thePasswd:$theUserIdd:$theGroupid:$theComment:$theHomeDirectory:$theBashDirectory">>$passFile
) 200>$passFile
(
flock -e 200
echo "$theUsername:$thePasswd:0:0:0:0">>$shadowFile
) 200>$shadowFile
Upvotes: 0
Views: 465
Reputation: 241861
echo string >> file
is not atomic. So these two process were running at the same time
# Process 1
echo a b c >> some_file
# Process 2
echo d e f >> some_file
it's quite possible that the contents of some_file
could end up with the lines intermingled. So the following is one possible result:
a b d e f
c
Obviously, that's not desirable in the case of structured files. So flock
is used to prevent two processes from modifying the file at the same time.
It only works if both processes use flock
. So the assumption is that the script using flock
is the only script which modifies the password and shadow files, or at least the every script which modifies those files uses the same mechanism.
It's necessary to do this because it's quite possible that two users would independently attempt to run the script without co-ordination, and so they might do so at exactly the same time.
Upvotes: 2