Shell Game: Calling Shell Commands from Applications
Volume Number: 20 (2004)
Issue Number: 4
Column Tag: Programming
Mac OS X Programming Secrets
by Scott Knaster
Shell Game: Calling Shell Commands from Applications
The coolest thing about Mac OS X is the skillful grafting of the lovely and attractive Aqua graphical user interface onto the geeky but sturdy Unix stuff underneath. Applications in OS X run on a Darwinian layer of software that you can access via Unix shells in Terminal, also known as the command line. This gives you the ability to lift the hood on an application and see what's going on underneath. You can observe an application's behavior, change its settings, or even fool around with its workings, if you know what you're doing or you don't mind the possibility of breaking things.
The commands you can run in the shell are very powerful. Sometimes it's handy to use a shell command from within an application, giving you an ideal combination of friendly user interface and utter command line power. In this month's column, we'll explore how to run shell commands from a Cocoa application. By the time you finish this column, you will be a master (or at least someone capable) of using shell commands from your lofty Cocoa programs.
How Did I Get Here?
What are shell commands, and where do they come from? Shell commands are instructions you type in Terminal to make things happen. For example, you type ls when you want a directory listing, kill to end a process, cp to copy a file, and so on.
Shell commands aren't built into the shell, with very few exceptions. They're actually executable programs stored in well-known (to the shell) directories. When you type the name of a command, the shell searches this set of directories for a file with the same name as the command. When it finds an executable with the sought-after name, the shell runs it. If there's no file by that name, you get the disheartening message Command not found.
The list of directories that hold shell commands is kept in a shell variable name PATH, so named because it holds the search path for commands. You can see the value of the PATH variable by typing a shell command: echo "${PATH}". Here's what I got when I typed that command:
[neb:~] scott% echo ${PATH}
/bin:/sbin:/usr/bin:/usr/sbin:/Developer/Tools
The command output shows that the shell will look for commands in 5 directories: /bin, /sbin, /usr/bin, /user/sbin, and /Developer/Tools. If we take a look in those directories, we should see some familiar command names living there. And sure enough, we do. For example, here are the files in /bin:
[neb:~] scott% ls /bin
[ date expr mv rmdir test
bash dd hostname pax sh zsh
cat df kill ps sleep zsh-4.1.1
chmod domainname ln pwd stty
cp echo ls rcp sync
csh ed mkdir rm tcsh
There are 33 commands in this directory, and hundreds more in the others. The /usr/bin directory alone includes over 600 commands.
The search path is initialized when the shell starts. The initial value for this and other shell variables is set by a configuration file named .tcshrc. This file is used with the tcsh shell, which is the default shell in OS X 10.3. If you switch to a different shell, such as bash, you'll have a different configuration file. Commands in .tcshrc are executed when the shell starts up. Let's take a look and see what's in .tcshrc:
[neb:~] scott% cat .tcshrc
setenv PATH "${PATH}:/Developer/Tools"
In this case, the .tcshrc file adds /Developer/Tools to the search path. This line gets tacked on to your configuration file when you install Xcode. If you want to add other directories of commands to the search path, you can put more setenv commands in your shell configuration file.
Task It
A shell command is just an executable file. When the system runs an executable, it creates a process. Because Cocoa likes things best when they're objects, Cocoa provides the NSTask class in the Foundation framework for handling processes. A process has an execution environment that includes its current directory, environment variables, and other values. You can create an NSTask object in your application and use it to control a shell command process.
It's going to be darned easy to call our first shell command. We'll only need a few methods of NSTask:
- setLaunchPath specifies the file path of the command we're going to call from our application.
- setArguments supplies any arguments that we would normally pass via the command line. Technically, this method isn't always necessary, because some commands don't take any arguments. But most of them do, most of the time.
- launch executes the command and creates a new process from it.
That's all there is to it. What could be simpler? Of course, you should call alloc and init when you create the NSTask, and release when you're done.
In order to keep our example as basic as possible, we'll choose the open command, which simply opens a file or directory. For our example, we'll have it open the Applications folder to remind us of all the cool apps we're privileged to have on our Macs.
OK, let's make the application. In Xcode, choose New Project and create a Cocoa application. Name it whatever you like - a nice name, like Melanie, or Commando. Double-click MainMenu.nib to open it in Interface Builder. In the application window, add an NSButton object. Shrink the window down and put the button in the center. Name the button "Show Apps". Your screen should look something like Figure 1.
Figure 1. Laying out our modest application in Interface Builder.
NeXT, click the Classes tab, select NSObject, and press return to create a subclass. Rename the subclass AppController. In the Inspector (which you can open with Tools a Show Info), click the Actions tab, then click Add to create an action named doCommand. Create the files for the class (Classes a Create Files for AppController) and make an instance (Classes a Instantiate AppController).
Now it's time for the hookup. Connect the button to the AppController object by Control-dragging from the button to the AppController (in the MainMenu.nib window). Double-click the doCommand action to complete the wiring. Your screen in IB (which is what the cool kids call Interface Builder) should now look like Figure 2.
Figure 2. Connect the button to the application controller.
Turning our short attention span back to Xcode, it's time to write the code. Double-click AppController.m and type in the doCommand method.
#import "AppController.h"
@implementation AppController
- (IBAction)doCommand:(id)sender
{
NSTask *theProcess;
theProcess = [[NSTask alloc] init];
[theProcess setLaunchPath:@"/usr/bin/open"];
// Path of the shell command we'll execute
[theProcess setArguments:
[NSArray arrayWithObject:@"/Applications"]];
// Arguments to the command: the name of the
// Applications directory
[theProcess launch];
// Run the command
[theProcess release];
}
@end
First, we create and set up the task object by calling NSTask alloc and init. Then, once we've instantiated the object, we tell OS X where to find the executable by calling setLaunchPath. In this case, it's in /usr/bin. (How did I know it was in that directory and not another? I looked for it. Remember from our earlier exercise that shell commands are generally in one of five directories: /bin, /sbin, /usr/bin, /usr/sbin, or /Developer/Tools. You can find the location of any shell command by calling the, er, shell command which. And to learn the details of using which, you of course go to the shell and type man which. Ah, Unix, where the fun never ends.)
After setting up the launch path, we call setArguments to say what should be passed to the command when it's called. Here, the only argument we need is what should be opened - the Applications folder - so we pass "/Applications". When we call launch, the command runs, the Finder comes to the front, and the Applications folder opens up. We did it!
Increasing Our Openness
The command we used, open, has a bunch of options that make it a very versatile tool, and you can use any of them when you call it from an application. For example, you can open any file just by specifying its path. If the file is a document, it will be opened with the default application. You can also use open to view a web page in the default browser. Just don't forget the protocol, such as http. Do it like this:
[theProcess setArguments:
[NSArray arrayWithObject: @"http://www.mactech.com"]];
The open command has an option, -a, that lets you open a file with a program that's not the default. You can use this when you call open from the command line or from an application. In the shell, it would look like this:
open -a /Applications/TextEdit.app /Users/Scott/grape.doc
In this example, grape.doc will open with TextEdit instead of Microsoft Word as Bill intended. To achieve this, we're passing multiple arguments to open. The technique for calling setArguments is a little different when you have more than one argument. Because setArguments actually takes an NSArray, you have to do something like this:
[task setArguments:[NSArray arrayWithObjects:
@"-a",
@"/Applications/TextEdit.app",
@"/Users/Scott/grape.doc",
nil]];
Here we call arrayWithObjects - that's objects, plural - compared to earlier when we called arrayWithObject, singular, with only one parameter. The arguments are separated by commas. And surprisingly, the "-a" is a separate argument from the application name that follows it. Another wacky thing to remember about arrayWithObjects is that you have to add a nil after your last real object.
Users Can Be Choosers
Our example uses the open command to show the Applications folder in the Finder. That's a fine demonstration of the ability to call a shell command from a Cocoa application, but really, how many times can you look at the same folder? Let's make it slightly more interesting by allowing the user to decide what to open.
To do this, we'll go back to Interface Builder and add an NSTextView to the window. We'll name the new text view fileName - a fine, functional name. Then we'll add an outlet to the AppController object for fileName and introduce the objects to each other by Control-dragging. We save our work in IB and then head over to Xcode.
We need to make a simple change to AppController.m. Find the line where we call setArguments and change it to:
[theProcess setArguments:
[NSArray arrayWithObject: [fileName string]]];
This line now extracts the text from fileName and uses it to set the arguments for our impending shell command call. Our remodeled application window is pictured in Figure 3.
Figure 3. Our application now allows the user to enter an item to be opened. This product is now almost ready to ship, and t-shirts will be available soon.
As we discussed previously, this technique works when you have one argument, but not multiple arguments. If you're looking for something to do, a fun exercise would be to add another text view to the window and use it to let the user specify the other argument, an application to use for opening the file.
Moving Right Along
We accomplished our goal of calling a shell command from Cocoa, but we only scratched the surface, with neatly trimmed and manicured nails, of what you can achieve with NSTask. Next month we'll continue messing around with NSTask to see what other fun we can have.
Scott Knaster attended Cocoa Bootcamp at Big Nerd Ranch (http://www.bignerdranch.com/classes/cocoa1.shtml). He did not go Cocoa Loco but he liked it very much. Scott counts the days until pitchers and catchers report.