Advertisement
Advertisement


shell script to remove a file if it already exist


Question

I am working on some stuff where I am storing data in a file. But each time I run the script it gets appended to the previous file.

I want help on how I can remove the file if it already exists.

2015/07/09
1
196
7/9/2015 1:55:01 PM


Another one line command I used is:

[ -e file ] && rm file
2018/05/07

You can use this:

#!/bin/bash

file="file_you_want_to_delete"

if [ -f $file ] ; then
    rm $file
fi
2015/07/09

If you want to ignore the step to check if file exists or not, then you can use a fairly easy command, which will delete the file if exists and does not throw an error if it is non-existing.

 rm -f xyz.csv
2017/05/24

A one liner shell script to remove a file if it already exist (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
2019/08/27

Something like this would work

#!/bin/sh

if [ -fe FILE ]
then 
    rm FILE
fi 

-f checks if it's a regular file

-e checks if the file exist

Introduction to if for more information

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

2015/07/09