I have a makefile within a C++ project (compiler: C++11). How can you check to see if a particular file exists before removing it with a makefile command?
Here is the code:
bin: charstack.h error.h
g++ -Wall -std=c++11 main.cpp charstack.cpp error.cpp -o bin
run:
./bin.exe
clean:
rm bin.exe
# This statement removes auto generated backups on my system.
cl:
rm charstack.h~ charstack.cpp~ main.cpp~ makefile~ error.h~ error.cpp~
How would I have the makefile check to see whether the auto generated .~ backup files exist before attempting to remove them when the user passes
make cl
in the command line? The goal here is to avoid outputting these errors to the terminal upon running "make cl":
rm: cannot remove `charstack.h~': No such file or directory
rm: cannot remove `charstack.cpp~': No such file or directory
rm: cannot remove `main.cpp~': No such file or directory
rm: cannot remove `error.h~': No such file or directory
rm: cannot remove `error.cpp~': No such file or directory
make: *** [cl] Error 1
Honestly, that's an XY problem, it is not due neither to the fact that the project is a C++ one nor that it uses the spec C++11.
Because of that, the title of the question is a bit misleading, as well as its tags.
Anyway, you can use the option -f
. From the man page of rm
:
ignore nonexistent files and arguments, never prompt
So, it's enough to use the following line:
rm -f charstack.h~ charstack.cpp~ main.cpp~ makefile~ error.h~ error.cpp~
Actually, it doesn't check if those files exist, but also it doesn't complain if they don't exist.
Even though this question has been answered, I attach a different solution that works for both files AND directories (because rm -rf DIRNAME
is not silent anymore)
Here is a rule for removing a directory in variable ${OUTDIR}
only if the directory exists. The example is easily adjusted for files:
clean:
if [ -d "${OUTDIR}" ]; then \
rm -r ${OUTDIR}; \
fi \
Note that the key observation is that you have to write the usual bash if-then-esle as if it where on a single line (i.e. using \
before a newline, and with a ;
after each command). The example can be easily adapted to different (non-bash) shells.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With