5

I tried to suppress an error from rm command by writing

Makefile:

...
clean: $(wildcard *.mod)
    -rm $^ 2>/dev/null
...

I ran:

$ make clean
rm  2>/dev/null
make: [clean] Error 64 (ignored)

I still had gotten an error.

Anyway, when I tried

$ rm [some non-existent files] 2>/dev/null

on the bash shell, it just works fine.

How can I use 2>/dev/null inside a makefile?

fronthem
  • 4,011
  • 8
  • 34
  • 55

2 Answers2

8

2>dev/null will redirect the error output so you don't see it, it will not prevent the shell to raise the error level. And the - sign in front of your shell command will tell GNU make to continue even if the error level is raised but it will not either prevent the shell to raise it.

What you want is the shell not to raise the error level and this can be done like this :

Unix (credits to this answer)

-rm $^ 2>/dev/null ; true

Windows

-rm $^ 2>NUL || true

or if you don't have rm on Windows

-del /F /Q $^ 2>NUL || true
Tim
  • 1,853
  • 2
  • 24
  • 36
5

The message make: [clean] Error 64 (ignored) is being printed by make after it sees that your shell command has failed. It will therefore not be affected by any redirection that you use in the recipe.

Two fixes:

  1. Use the -f rm flag. rm -f never returns an error. (Well, hardly ever anyway, and if it does you probably want to know about it!)

  2. Stop the shell command returning an error: simply append || : to the command. Say what? Well if the rm succeeds your job is done and make is happy. OTOH if rm fails, the shell runs the second command in the or. : is a shell built-in that always succeeds, and is much preferable to true IMHO.

The first of these is best in this case, though the second is a general, if somewhat less efficient, pattern.

.PHONY: clean
clean: ; rm -rf *.mod
bobbogo
  • 14,989
  • 3
  • 48
  • 57