在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 thenoclobber
option to theset
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中的所有内容).