bash脚本中不存在的原子创建文件 [英] atomic create file if not exists from bash script
问题描述
在系统调用open()
中,如果我用O_CREAT | O_EXCL
打开,则系统调用确保仅在文件不存在时才创建该文件.系统调用保证原子性.是否有类似的方法可以通过bash脚本以原子方式创建文件?
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
- 使用set -o noclobber.然后,您可以原子地使用>运算符.
- 只需使用mkdir. Mkdir是原子的
推荐答案
一种100%纯bash解决方案:
A 100% pure bash solution:
set -o noclobber
{ > file ; } &> /dev/null
如果不存在名为file
的文件,此命令将创建一个名为file
的文件.如果有一个名为file
的文件,则什么也不做(但返回一个非零的返回码).
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).
使用touch
命令的专业人员:
- 如果文件已经存在,则不更新时间戳
- 内置100%bash
- 按预期方式返回代码:如果
file
已经存在或无法创建file
,则失败.如果file
不存在且已创建,则成功.
- Doesn't update timestamp if file already existed
- 100% bash builtin
- Return code as expected: fail if
file
already existed or iffile
couldn't be created; success iffile
didn't exist and was created.
缺点:
- 需要设置
noclobber
选项(但是在脚本中可以,如果您对重定向很小心,或者事后取消设置).
- need to set the
noclobber
option (but it's okay in a script, if you're careful with redirections, or unset it afterwards).
我想这个解决方案确实是open
系统调用O_CREAT | O_EXCL
的bash对应版本.
I guess this solution is really the bash counterpart of the open
system call with O_CREAT | O_EXCL
.
这篇关于bash脚本中不存在的原子创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!