Avoid "rm" in makefile

3

I have a question concerning a line in a Makefile. I have a target to "clean" my locally installed test/staging-server. Currently it looks like this:

clean:
    rm -rf $(LOCAL_SERVER_PATH)/*

As long as the variable LOCAL_SERVER_PATH is defined and looks like /srv/www/htdocs or something like this, everything is fine. But ... what if a user made a mistake and mistyped the variable-definition, or some config-step went rouge, and the Makefile is created, with a wrong definition.

Essentially, I fear, that by mistake I could end up with a non-defined $(LOCAL_SERVER_PATH), and my target would then yield to:

clean:
    rm -rf /*

Is it possible to refactor my Makefile to make it more robust against such errors? I don't want to end up with a Makefile, that could potentially wipe out my entire linux-installation (or even parts of it, since my user is not 'root').

Mathias Vonende

Posted 2015-06-10T15:54:17.180

Reputation: 133

5You could just check the variable beforehand, you know? ;) – Daniel B – 2015-06-10T15:57:05.750

Answers

3

As noted, check the variable to ensure that it is not empty:

clean:
    test -n "$(LOCAL_SERVER_PATH)" && rm -rf $(LOCAL_SERVER_PATH)/*

The same idiom appears in a large number of RPM spec-files, where it seems that the BUILD_ROOT variable has been known to be unset. Since its replacement is not universally available (despite the comments a while back in Re: [Fedora-packaging] Phase out buildroot?), it can still be found here and there.

Thomas Dickey

Posted 2015-06-10T15:54:17.180

Reputation: 6 891

2You may want to also check for '..' and ';' in the variable also if your paranoid, else a variable of '../../../../../../../' makes a sad panda. – Sirex – 2015-06-10T23:03:38.357

If you were truly paranoid, you would not cleanup in a makefile. I was reading one of those last night, for a code review. – Thomas Dickey – 2015-06-10T23:19:03.777