Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a file if it does not exist and write 0 in this file, otherwise do nothing [closed]

Tags:

linux

bash

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
like image 277
Lenoir Avatar asked Nov 17 '25 04:11

Lenoir


1 Answers

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 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.

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).

like image 84
gniourf_gniourf Avatar answered Nov 20 '25 05:11

gniourf_gniourf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!