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

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
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
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer 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 MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Apr 20, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.