Have rm not report when a file is missing?

Use the -f option. It will silently ignore nonexistent files.

From man rm:

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

[The "never prompt" part means that (a) -f overrides any previously specified -i or -I option, and (b) write-protected files will be deleted without asking.]

Example

Without -f, rm will complain about missing files:

$ rm nonesuch
rm: cannot remove ‘nonesuch’: No such file or directory

With -f, it will be silent:

$ rm -f nonesuch
$

If your requirement is that rm does not complain about missing files, but that you also want any other output from rm, my suggestion would be to first test for the target file's existence, and only call rm (without the -f flag) if the file actually exists.

# rest of script
# ...
[ -e "$file" ] && rm "$file"
# ...
# rest of script

Calling rm -f on a file that, for example, doesn't have user-write permissions, will remove the file and also not emit the normal prompt for that scenario.

In case you wanted to use the same idea with multiple files, I would create a function definition, like:

qrm() {
  for f
  do
    [ -e "$f" ] && rm "$f"
  done
}

Use it like: qrm file1 file2-does-not-exist *.txt etc here


You stated that you still want to see other output from the rm command when you run it, but using the -f option will suppress those. You will need to filter STDERR for what you want, which is a little tricky, given you want everything else to show.

You will want to use a command like this:

rm -f filename 3>&1 1>&2 2>&3 3>&- | grep -v 'No such file or directory'

Command explained:

  • -f argument is to force through and not prompt for confirmation or errors
  • 3>&1 1>&2 2>&3 3>&- is to switch around STDOUT and STDERR for filtering (you can read more about this here if wanted
  • | grep -v 'No such file or directory' is filtering out the message you do not want to see

Now, if you just wanted to suppress error messages entirely, you could run the following command:

rm filename 2> /dev/null

This command redirects STDERR to /dev/null so you will not see it when you run the command.

Tags:

Rm