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?
Well, it's entirely impossible to remove a file that doesn't exist, so it seems that the concept of "delete a file only if it exists" is redundant. So, rm -f filename , or rm filename 2>> /dev/null , or [[ -r filename ]] && rm filename would be some options..
You can apply the 'rm' command to remove an existing file. In the following script, an empty file is created by using the 'touch' command to test 'rm' command. Next, 'rm' command is used to remove the file, test.
files. deleteifexists(Path p) method defined in Files package: This method deletes a file if it exists. It also deletes a directory mentioned in the path only if the directory is not empty. Returns: It returns true if the file was deleted by this method; false if it could not be deleted because it did not exist.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With