Delete files in directory without erroring if it’s already empty

filesrm

As part of a deployment script, I want to dump some cached stuff from my temp directory. I use a command like:

rm /tmp/our_cache/*

However, if /tmp/our_cache is empty (fairly common when pushing many changes in quick succession to our testing server), this prints the following error message:

rm: cannot remove `/tmp/our_cache/*': No such file or directory

It's not a big deal, but it's a little ugly and I want to cut down the noise-to-signal ratio in the output from this script.

What's a concise way in unix to delete the contents of a directory without getting messages complaining that the directory is already empty?

Best Answer

Since you presumably want to remove all files without prompting, why not just use the -f switch to rm to ignore nonexistent files?

rm -f /tmp/our_cache/*

From man page:

-f, --force
          ignore nonexistent files, never prompt

Also, if there may be any subdirectories in /tmp/our_cache/ and you want those and their contents deleted as well, don't forget the -r switch.

Related Question