In system call open(), if I open with O_CREAT | O_EXCL, the system call ensures that the file will only be created if it does not exist. The atomicity is guaranteed by the system call. Is there a similar way to create a file in an atomic fashion from a bash script?
UPDATE: I found two different atomic ways
A 100% pure bash solution:
set -o noclobber
{ > file ; } &> /dev/null
This command creates a file named file if there's no existent file named file. If there's a file named file, then do nothing (but return a non-zero return code).
Pros wrt the touch command:
file already existed or if file couldn't be created; success if file didn't exist and was created.Cons:
noclobber option (but it's okay in a script, if you're careful with redirections, or unset it afterwards).I guess this solution is really the bash counterpart of the open system call with O_CREAT | O_EXCL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With