Home » Questions » Computers [ Ask a new question ]

How do I make rm not give an error if a file doesn't exist?

How do I make rm not give an error if a file doesn't exist?

I'm writing a makefile that will clean up some useless files at the end of the compilation. If a target has already been made, it will of course skip that target and the useless file may not be there. So if I do this:

Asked by: Guest | Views: 262
Total answers/comments: 5
bert [Entry]

"The -f option is definitely what you want to be using.

The confirmation about file permissions it refers to is this:

$ touch myfile
$ chmod 400 myfile
$ rm myfile
rm: remove write-protected regular empty file `myfile'?

So rm will warn you if you try to delete a file you don't have write permissions on. This is allowed if you have write permissions on the directory but is a little weird, which is why rm normally warns you about it."
bert [Entry]

"I'm way late to the party, but I use this all the time. In a makefile, add - to the beginning of a line to ignore the return value of that line. Like so:

-rm lexer.ml interpparse.ml interpparse.mli"
bert [Entry]

"The -f option means that you will not be prompted if something is not as expected. It does not mean that permissions are not taken into account.

If you have not enough privileges to remove a file, it won't be removed.

BUT, if you have enough privileges to change privileges, you file will be removed. This is the case when you are the owner of a file with readonly permissions for owner (-r--------). As owner, you can chmod u+w, then remove it: rm -f will remove that file."
"The -f option means that you will not be prompted if something is not as expected. It does not mean that permissions are not taken into account.

If you have not enough privileges to remove a file, it won't be removed.

BUT, if you have enough privileges to change privileges, you file will be removed. This is the case when you are the owner of a file with readonly permissions for owner (-r--------). As owner, you can chmod u+w, then remove it: rm -f will remove that file."
bert [Entry]

"Maybe could help a line similar with:

touch fakefile.exe fakefile.o && rm *.o *.exe

I know that this is not very smart, but it does the job."
bert [Entry]

"An alternative:

RmIfIsFile() { for f in ""$@""; do [ -f $f ] && rm $f; done; }; RmIfIsFile lexer.ml interpparse.ml interpparse.mli

Too bad Makefiles can't share shell function definitions across lines."