linux - 如果文件不存在则创建一个文件并在该文件中写入0,否则什么都不做

标签 linux bash

<分区>

在 Bash 中,我想检查一个文件是否存在,如果存在,什么也不做。如果不是,则创建一个新文件并在这个新文件中写入“0”。

我写了下面的代码,问题是:这段代码会覆盖现有的文件。谁能告诉我哪里错了?我该如何修改?

for r in FE C CR MN SI NI CO MO W NB AL P CU TA V B N O S
do
  if [ ! -f id1/data/T1_FCC_X_${r}.dat ]; then
    echo "0"  > data/T1_FCC_X_${r}.dat
  fi
done

最佳答案

您可以使用 noclobber 一次性完成选项:

Prevent output redirection using >, >&, and <> from overwriting existing files.

来自Redirecting Output section :

If the redirection operator is >, and the noclobber option to the set builtin has been enabled, the redirection will fail if the file whose name results from the expansion of word exists and is a regular file.

所以应该这样做:

set -o noclobber  # or, equivalently, set -C

for r in FE C CR MN SI NI CO MO W NB AL P CU TA V B N O S; do
    echo "0" > "data/T1_FCC_X_$r.dat"
done 2> /dev/null

如果文件存在,重定向将失败并显示标准错误消息(并且文件根本不会被覆盖);这就是我们将错误消息重定向到 /dev/null 的原因(在循环之后),以免污染标准错误流。

如果文件不存在,那么将执行重定向,前提是您拥有创建此类文件的所有权限。

注意。您可能想要取消设置 noclobber之后:set +o noclobber (或将所有内容都包含在子外壳中)。

关于linux - 如果文件不存在则创建一个文件并在该文件中写入0,否则什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54504650/

相关文章:

python - 处理文件名中的文字空间

linux - 将 shell 脚本和 zip 文件组合成一个可执行文件以进行部署

linux - 如果子进程在后台启动并且父进程已经退出,如何知道父进程

linux - 当在内部使用 bash 变量时,awk 命令无法按预期工作

c - 函数签名中的 restrict 是什么意思?

linux - 如何增加 boxfuse 中打开文件的用户限制?

linux - Dockerfile 在构建时找不到 shell 脚本

linux - bash 中的变量比较

string - 找到模式并将其移至行尾

linux - 在shell中获取程序执行时间