Thursday, February 12, 2009

Scripting on a Mac

Today I was working on a homework assignment for a class on distributed technologies (programming with networks) and I had to do go through a multistep process to compile and run the server and client programs. So I figured it would be easier to write two scripts that would do the leg work for me. I used to do this on my Windows computer using batch files. I hadn't done this before on a Unix based machine so it took a little bit of research.

I opened up TextEdit since I was using my main text editor Smultron for the Java files I was working on and didn't want to mix them. The first line of my two scripts each looked like this: "#!/bin/bash". This will tell the system which shell to use. Unix has a bunch of different shell options (bash, tcsh, zsh, sh, csh, ksh). The default for OS X is bash and that is the one I decided to stick with. The second line of each of my scripts was a cd command to change directory. Sure, I could have eliminated this step by including a full path in the following lines or my moving my script to a different directory, but I wanted to place my scripts in the root of my home directory as that is the starting location when you open a new Terminal session.

In Unix, there are three basic file permissions, there is read (r), write (w), and execute (x). Default permissions for newly created files are rw-, meaning read and write only, but not executable. In order to change this so that my newly creates scripts were executable, I opened up Terminal and typed "chmod +x [script name]" (file extensions are not necessary when naming scripts, but make sure you include it if you gave your script one). Chmod stands for "change mode" and is used to change permissions on files and directories.

Once a script is executable, there are two ways to run them. Just opening the script from Finder will open the script with a new Terminal session and run it. Alternatively, the scripts can be run from an existing Terminal session. Since I was working with a console based Java program, I wanted to run them from Terminal. The Unix command to run an executable from the shell is "./[script name]".

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.