in Development by (16.3k points)
0 like 0 dislike

I am working on some stuff where I am storing data in a log file. But each time I run the script it gets appended to the previous file content. I want help on how I can remove the file if it already exists. How I can to remove a file if it already exist in bash? How to clear contents of a file or delete whole file from the command line?

bash clear file if exists

1 Answer

0 like 0 dislike
by (16.3k points)
if [ -f $file ]; then
    rm $file

In variable file are path to file what you want to delete.

Don't bother checking if the file exists, just try to remove it:

rm -f /path/file


rm /path/file 2> /dev/null

Another one line command:

[ -e file ] && rm file

Please log in or register to answer this question.