atomic create file if not exists from bash script

前端 未结 6 1664
盖世英雄少女心
盖世英雄少女心 2020-12-15 22:24

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 atomic

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 22:53

    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.

提交回复
热议问题