Xcode run script

There always comes a time in the life of a iOS developer when it has to create a for various reasons a script to automate a certain task. For example, you can create a script on your production target that every time you make an production build your localisable files will be stripped of unused keys, this was a simple example but you can create more complex functionalities with this feature of Xcode.

How do you create an run script?

 

screen-shot-2016-09-24-at-13-04-19

 

 

screen-shot-2016-09-24-at-13-04-39

 

 

screen-shot-2016-09-24-at-13-05-16

 

 

 

 

 

Thats it, simple as that.

 

Now lets talk about what can we write in here.

What sort of scripting language can we use, we can use basically any type of scripting language that comes installed on macOS, a few example would be:

/bin/bash
/bin/csh
/bin/sh

Another great thing, which I found out from an Stackoverflow post, is the fact that we can specify input and output files. Basically we can tell Xcode which file we are going to read in our script so that the build script is run ONLY if one of those files has changed, if the files haven’t changed Xcode caches the result, so it won’t affect the build time. Output files are the files out script writes to, we specify those so that if they haven’t changed, Xcode can cache the build.

One specifically thing worth mentioning, is the fact that the order of the build phases, matters, so if you want your script to be run before the compile phase, you can do that by dragging it before the compile phase.

If you follow the 3 images in this post you will have a project which when you’ll run it it will produce a file named myFile.txt in the root of your project with the content “Hello world”, while this is useful, sometimes when you are writing your script, you need to check the output of the commands. If you modify the script by deleting “> myFile.txt”, the result will be just ‘echo “HelloWorld”‘, if we delete the initial file and run the project again, no file will be generated and we can no longer see the output. In order for us to see the output of the script, we need to access the Report navigator in Xcode and select the build phase.

screen-shot-2016-09-24-at-13-34-57

 

 

 

 

Last but not least, you can use many path variables and even git commands to fetch any details about your project repo.