How can I delete a file only if it exists?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)