Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent rm from reporting that a file was not found?

Tags:

bash

rm

People also ask

How can accidental rm be prevented?

One of the tricks I follow is to put # in the beginning while using the rm command. This prevents accidental execution of rm on the wrong file/directory. Once verified, remove # from the beginning.

Does rm actually delete the file?

Does rm Delete a File? Actually, the rm command never delete a file, instead it unlinks from the disk, but the data is still on th disk and can be recovered using tools such as PhotoRec, Scalpel or Foremost.


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.


Yes, -f is the most suitable option for this.


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


\rm -f file will never report not found.


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.