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

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom 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.