Shell script to delete a file if it already exists

I am working on some materials where I store data in a file. But every time I run the script, it is added to the previous file.

I need help on how I can delete a file if it already exists.

+147
shell
Jul 09 '15 at 12:50
source share
7 answers

Do not try to check if the file exists, just try deleting it.

rm -f /p/a/t/h # or rm /p/a/t/h 2> /dev/null 

Note that the second command will fail (return a non-zero completion status) if the file does not exist, but the first will succeed thanks to -f (short for --force ). Depending on the situation, this can be an important detail.

But most likely, if you add a file, it is because your script uses >> to redirect something to the file. Just replace >> with > . It’s hard to say since you did not provide the code.

Note that you can do something like test -f/p/a/t/h && rm/p/a/t/h , but doing this is completely pointless. It is possible that the test will return true, but / p / a / t / h will not exist before you try to delete it, or, even worse, the test will fail and / p / a / t / h will be created. before executing the next command, which expects it to not exist. Trying is a classic race condition. Do not do this.

+135
Jul 09 '15 at 12:59 on
source share

Another line I used is:

 [ -e file ] && rm file 
+103
Jul 13 '16 at 21:34
source share

You can use this:

 #!/bin/bash file="file_you_want_to_delete" if [ -f $file ] ; then rm $file fi 
+71
Jul 09 '15 at 12:58
source share

If you want to ignore the step to check if the file exists or not, you can use a fairly light command that will delete the file if it exists and does not throw an error if it does not exist.

  rm -f xyz.csv 
+53
May 12 '17 at 9:46 a.m.
source share

Something like this will work

 #!/bin/sh if [ -fe FILE ] then rm FILE fi 

-f checks if it is a regular file

-e checks if the file exists

Introduction to for more information

EDIT: -e used with -f is redundant, fo using -f should work too

+13
Jul 09 '15 at 12:56
source share

A shell script with one liner to delete a file if it already exists (based on Jindra Helcl's answer):

[ -f file ] && rm file

or with a variable:

 #!/bin/bash file="/path/to/file.ext" [ -f $file ] && rm $file 
+8
Dec 07 '18 at 14:21
source share

if [ $( ls <file> ) ]; then rm <file>; fi

Also, if you redirect your output with > instead of >> , it will overwrite the previous file

+3
Apr 20 '16 at 18:27
source share



All Articles