Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

c - atomic create file if not exists from bash script

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

  1. Use set -o noclobber. Then you can use > operator atomically.
  2. Just use mkdir. Mkdir is atomic
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  • Doesn't update timestamp if file already existed
  • 100% bash builtin
  • Return code as expected: fail if file already existed or if file couldn't be created; success if file didn't exist and was created.

Cons:

  • need to set the 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...