Sunday, August 26, 2012

The OSX equivalent of simple batch files


As a Windows developer, one of the biggest hurdles in getting into iOS (Xcode) development is getting used to a whole new OS. Silly little tasks suddenly take up a significant amount of time, and because you mentally consider them "trivial", you completely underestimate the impact this has on daily development. Because zero minutes times a lot is still zero, right?

One of those tasks is using batch files for simple stuff. Stuff like zipping up a bunch of folders and copying them somewhere else. Deleting some files with specific names. Kids' stuff, basically.

Enter Mac OSX. It is based on Unix, meaning it has a terminal and does shell scripts. As any Unix guy will tell you, Unix shell script runs circles around  Windows batch script. It's like a full-fledged class IV intergalactic battle cruiser to our granny bike. The problem is: I just want to get to the grocery store today.

The first thing you need to realize is that Windows batch files execute from the Windows Explorer really nicely. We consider this a given, but you don't get this stuff for free on OSX.

Here is a little step-by-step on how to create the equivalent of a batch file on OSX. Make sure to open up a terminal and navigate to the required folder first.

Step 1) Create a new file (copy con test.bat).
 touch test.command  
Touch can be used to create a file out of thin air. Do note the .command extension: this is a known file association for Finder, allowing you to actually click it to run it. Using the regular .sh for shell scripts will not work.

Step 2) Mark the file as executable (no batch equivalent)
chmod +x test.command  

Step 3) Open up the file in the text editor of choice of the OS (notepad test.bat)
open -a TextEdit test.command  

Step 4)
Start the script in the current folder (the default in batch ), by opening with
cd "$(dirname "$0")" 
The double quotes take care of any spaces in filenames. The $( ) performs an inline command execution. It executes the dirname command to parse the directory from the full path argument passed in $0 (by Finder)

Step 5) Fill out the rest of the script to do something useful
cd "$(dirname "$0")"
[insert useful stuff here] 

Step 6) Save the script using command-s.

You now have a nice little script that can be execute from Finder. If you want to execute it from the terminal directly, make sure to prefix it with the current folder (./test.command).

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete