Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete a file only if it exists?

Tags:

shell

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?

like image 262
user7649922 Avatar asked Mar 07 '17 18:03

user7649922


People also ask

How do you remove a file only if it exists?

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..

How do you remove a file only if it exists in bash?

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.

How do you delete a file if it exists Java?

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.


1 Answers

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.

like image 200
Charles Duffy Avatar answered Oct 15 '22 00:10

Charles Duffy