How to prevent rm from reporting that a file was not found?
BashRmBash Problem Overview
I am using rm
within a BASH script to delete many files. Sometimes the files are not present, so it reports many errors. I do not need this message. I have searched the man page for a command to make rm
quiet, but the only option I found is -f
, which from the description, "ignore nonexistent files, never prompt", seems to be the right choice, but the name does not seem to fit, so I am concerned it might have unintended consequences.
- Is the
-f
option the correct way to silencerm
? Why isn't it called-q
? - Does this option do anything else?
Bash Solutions
Solution 1 - Bash
The main use of -f
is to force the removal of files that would
not be removed using rm
by itself (as a special case, it "removes"
non-existent files, thus suppressing the error message).
You can also just redirect the error message using
$ rm file.txt 2> /dev/null
(or your operating system's equivalent). You can check the value of $?
immediately after calling rm
to see if a file was actually removed or not.
Solution 2 - Bash
Yes, -f
is the most suitable option for this.
Solution 3 - Bash
-f is the correct flag, but for the test operator, not rm
[ -f "$THEFILE" ] && rm "$THEFILE"
this ensures that the file exists and is a regular file (not a directory, device node etc...)
Solution 4 - Bash
\rm -f file
will never report not found.
Solution 5 - Bash
As far as rm -f
doing "anything else", it does force (-f
is shorthand for --force
) silent removal in situations where rm
would otherwise ask you for confirmation. For example, when trying to remove a file not writable by you from a directory that is writable by you.
Solution 6 - Bash
I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.