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

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(或包含子shell中的所有内容).

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...