user7649922
user7649922

Reputation: 633

How can I delete a file only if it exists?

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?

Upvotes: 55

Views: 66953

Answers (4)

Alex Montoya
Alex Montoya

Reputation: 5119

You can use

To delete a directory

rm -rf my/dir || true

To delete a file

rm my/file || true

|| true works if the file/directory does not exist and does not throw an error

Upvotes: 1

mahemoff
mahemoff

Reputation: 46509

Touch the file first, which will create it if it's not present, but only change the timestamp if it is present.

touch filename && rm filename

Less efficient, but easy to remember.

Upvotes: 11

Rajesh Dwivedi
Rajesh Dwivedi

Reputation: 370

if [ ! -f 'absolute path of file' ]
then
  echo "File does not exist. Skipping..."
else
  rm 'absolute path of file'
fi

If you use the following then it should work.

Upvotes: 5

Charles Duffy
Charles Duffy

Reputation: 295934

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.

Upvotes: 128

Related Questions