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

Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »

Price Scanner via MacPrices.net

Verizon has Apple AirPods on sale this weeken...
Verizon has Apple AirPods on sale for up to 31% off MSRP on their online store this weekend. Their prices are the lowest price available for AirPods from any Apple retailer. Verizon service is not... Read more
Apple has 15-inch M2 MacBook Airs available s...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
May 2024 Apple Education discounts on MacBook...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $300 off the purchase of a new MacBook... Read more
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.