kelan.io

Run Script While Cleaning in Xcode

A recent comment reminded me that I alluded to a way to call scripts when Cleaning a target in your Xcode project, as opposed to a normal “Run Script Build Phase”, which does not get run during a clean. So, here is how you do it. I admit, it’s a bit of a hack (in a good way, I like to think), but it gets the job done, and I couldn’t find any other way to accomplish this.

Overview

The trick is that you create a new “External Target”, and set that as a dependency of your main target. This External Target lets you run any script (if you change the “tool” from /usr/bin/make to /bin/sh) and, most importantly, will get run while Cleaning (with the $ACTION environment variable set to “clean”).

Setup Instructions

The Script

You can have this script do anything you want, just like a “Run Script Build Phase”, but the important difference is that it gets called for Clean actions too. So, you want to make your script check for that (by checking the $ACTION environment variable). I do it like this:

externalScript.sh

#! /bin/sh

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# ACTIONS
# These are implemented as functions, and just called by the
# short MAIN section below

buildAction () {
    echo "Building..."

    # You might want to call your clean action first, if it makes sense.
    cleanAction

    # Now do build steps.

}

cleanAction () {
    echo "Cleaning..."

    # Do your clean steps here.
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# MAIN

echo "Running with ACTION=${ACTION}"

case $ACTION in
    # NOTE: for some reason, it gets set to "" rather than "build" when
    # doing a build.
    "")
        buildAction
        ;;

    "clean")
        cleanAction
        ;;
esac

exit 0

Indicating Errors

If you have your script exit with a non-zero exit value (i.e. exit 1), Xcode will halt the build. Furthermore, if you print output that starts with “error: ”, Xcode will show that in the Build Results window, like so:

Notes and Limitations

Alright, that’s it. Let me know if you have any questions or suggestion on how to improve this.