Monday, January 29, 2024

[SOLVED] How can I delete a file only if it exists?

Issue

I have a shell script and I want to add a line or two where it would remove a log file only if it exists. Currently my script simply does:

rm filename.log

However if the filename doesn't exist I get a message saying filename.log does not exist, cannot remove. This makes sense but I don't want to keep seeing that every time I run the script. Is there a smarter way with an IF statement I can get this done?


Solution

Pass the -f argument to rm, which will cause it to treat the situation where the named file does not exist as success, and will suppress any error message in that case:

rm -f -- filename.log

What you literally asked for would be more like:

[ -e filename.log ] && rm -- filename.log

but it's more to type and adds extra failure modes. (If something else deleted the file after [ tests for it but before rm deletes it, then you're back at having a failure again).

As an aside, the --s cause the filename to be treated as literal even if it starts with a leading dash; you should use these habitually if your names are coming from variables or otherwise not strictly controlled.



Answered By - Charles Duffy
Answer Checked By - Cary Denson (WPSolving Admin)