bash脚本中不存在的原子创建文件 [英] atomic create file if not exists from bash script

查看:97
本文介绍了bash脚本中不存在的原子创建文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在系统调用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

  1. 使用set -o noclobber.然后,您可以原子地使用>运算符.
  2. 只需使用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 if file couldn't be created; success if file 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆