in Programming by (10.8k points)
0 like 0 dislike
30 views

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 (10.8k points)
file="/path/to/file"
if [ -f $file ]; then
    rm $file
fi

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

or

rm /path/file 2> /dev/null

Another one line command:

[ -e file ] && rm file

Your answer

Try to answer the question as detailed as possible.
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.