TweetFollow Us on Twitter

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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.