In Bash, I want to check if a file exists, if exist, do nothing. If not, create a new file and write "0" in this new file.
I wrote the following code, The problem is: this code will overwrite the existing file. Could anyone tell me where is wrong? How should I revise it?
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
You can do it in just one shot with the noclobber option:
Prevent output redirection using
>,>&, and<>from overwriting existing files.
From the Redirecting Output section:
If the redirection operator is
>, and thenoclobberoption to thesetbuiltin has been enabled, the redirection will fail if the file whose name results from the expansion of word exists and is a regular file.
So this should do:
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
If the file exists, the redirection fails with an error message on standard error (and the file isn't overwritten at all); that's why we redirect the error message to /dev/null (after the loop), so as to not pollute the standard error stream.
If the file doesn't exist, then the redirection will be performed, provided that you have all the rights to create such a file.
Note. You might want to unset noclobber after this: set +o noclobber (or include everything in a subshell).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With