MakeFile Backup Target

Goal: I'm trying to create a PHONY target inside my Makefile so that when I run the command "make backup",
It will move all the files that end in "~" into the specified backup folder.

Here is my code currently, and I'll explain the problem after:

.PHONY: backup
backup:
    @mkdir -p ./backup/include    #make folder (don't complain if it already exists)
    @mkdir -p ./backup/src        #make folder (don't complain if it already exists)
    @mv -fu *.h~ ./backup/include #move header file backups into desired folder
    @mv -fu *.cpp~ ./backup/src   #move source file backups into desired folder

Problem: This works great, BUT ONLY if a file ".h~" and ".cpp~" file already exist in Makefile's current directory. I would like this target to move the files if it can, and just be quiet if there are no files to move..

Error Message: mv: cannot stat `*.h~': No such file or directory

*I'm on linux(ubuntu) and so my shell is "bash"

Appreciate the help, I've been stuck on this all night trying all kinds of commands from if statements to the "find" command. Just thought I'd finally ask for some assistance

This might do the trick:

    @mv -fu *.h~ ./backup/include/ >/dev/null 2>&1 || true

The redirection tosses any errors away, and the ||true causes any error return value from mv to be ignored. From make's perspective, the command is always successful because of the addition of the true statement.

The risk here, is that if the files exist, and cannot legitimately be moved, you'll not see the errors. If you're concerned about that, then this should also work though it might be less efficient, but I don't think you'll notice.

@if  ls *.h~ >/dev/null 2>&1; then mv -fu *.h~ backup/include/; fi

Again redirection hides any errors from ls. This time the status of mv, will be noticed by make, but there won't be any 'false alarms' because mv won't be invoked unless those files exist. If the true branch of the if isn't taken, make should see the command as having been successful.

Beautiful! thanks for the great answer