Vincent Gable’s Blog

March 5, 2008

Calling the Command Line from Cocoa

Filed under: Cocoa,MacOSX,Objective-C,Programming,Tips,UNIX | , , , ,
― Vincent Gable on March 5, 2008

The best way to call a shell-command from Coca is by using an NSTask. Here are the three resources on using an NSTask that I found the most helpful:
CocoDev’s write up
A few quick exaples
NSTask Class Refrence

And here is some sample code to do it for you. You are free to use this code however you please, but attribution is always appreciated. The two principle functions are:

+ (NSString*) executeShellCommandSynchronously:(NSString*)command executes the command “command” with sh, wait until it finishes, and return whatever it printed to stdout and stderr as an NSString.
CAUTION: may deadlock under some circumstances if the output gets so big it fills the pipe. See for an overview of the problem, and a solution. I have not experienced the problem myself, so I can’t comment.

executeShellCommandAsynchronously: will have sh execute command in the background, without blocking anything.

For quick hacks, the POSIX int system(const char* command) function, might be a good one-line solution. It synchronously evaluates command with sh.


EDITED 2009-11-29: this code probably won’t have the same $PATH you would get if you used Terminal. See this question on stackoverflow for more details. A solution that seems to work is to do,

    [task setLaunchPath:@"/bin/bash"];
    NSArray	*args = [NSArray arrayWithObjects:@"-l",
    [task setArguments: args];

This launches bash (not in sh compatibility mode), and -l (lowercase L) tells it to “act as if it had been invoked as a login shell”. I haven’t tested this on systems where bash isn’t the default shell. There are lots of ways $PATH could be set, and I haven’t tested them all. But you are almost certainly going to be OK if everything you refer to is in /usr/bin:/bin:/usr/sbin:/sbin.


  1. […] you can’t tell yourself to start up when you aren’t running. Here is one solution, use NSTask to run a very short script that you can embed right in your Objective-C code: kill -9 YourPID open […]

    Pingback by Vincent Gable » Restarting Your Cocoa Application — October 5, 2008 @ 7:35 pm

  2. Thanks! Your ShellTask class was just what I needed.

    Comment by Jack Repenning — November 13, 2008 @ 6:45 am

  3. Thanks. This is great! Is there a way to execute several commands within the same Terminal session? I’m calling executeShellCommandSynchronously multiple times to traverse folders and and retreive contents of a file:

    cd /
    cd Users/theuser/Thefolder
    vi somefile.txt

    The problem is that each command executes in its own Terminal session. So the second command gives a folder not found because I’m still in the build/debug folder. Any suggestions? Thanks.

    Comment by Xcode newbie — January 19, 2009 @ 9:47 am

  4. What I would suggest doing is putting those dependent shell commands together in their own shell script, and then executing the shell script.
    Once you have added the script,, to your Xcode project, you can have the shell run it like:

    NSString *pathToMyScript = [[NSBundle mainBundle] pathForResource:@”MyScript” ofType:@”sh”];
    [[NSTask launchedTaskWithLaunchPath:@”/bin/sh” arguments:[NSArray arrayWithObject:pathToMyScript]] waitUntilExit];

    Comment by Vincent Gable — January 19, 2009 @ 7:33 pm

  5. Thanks. This is getting off topic but I’d like to run some sqlite commands. After executing folder change commands in the .sh file, these commands execute:

    sqlite3 myDB.sqlite
    .import dbArea.txt Area

    When I run the .sh file from Terminal, I’m at an sqlite prompt. The import command doesn’t execute. Any ideas what’s going on?

    Comment by Xcode newbie — January 20, 2009 @ 10:11 am

  6. Used to get the primary mac address of the computer in order to run an mathematical permutation to get a unique “computer code”

    Comment by Alex Akers — February 15, 2009 @ 1:29 pm

  7. Great post! I’ve also noticed a huge craze in Facebook quotes, there were a few sites that would get millions of likes just on a single quote.

    Comment by Eminem Quotes — August 19, 2011 @ 8:16 pm

  8. great post save up the great work.

    Comment by at&t outlook settings — November 23, 2011 @ 10:30 pm

  9. I believe other website owners should take this site as an model, very clean and fantastic user friendly design and style .

    Comment by fioricet — February 6, 2012 @ 11:21 pm

  10. Your ShellTask class has made a project I’m doing so much simpler and I thank you greatly for it. My application is using a CLI API for a 3rd party product and thus is making quick CLI calls back and forth in rapid succession. I needed a good way to do synchronous calls much like I would do in a shell script or perl inside of a loop and your class works perfectly for my needs. I know it has been 5 years since you wrote it, but it is still very useful.

    Comment by Mike — March 7, 2012 @ 4:47 am

  11. I do not even know how I stopped up right here, but I believed this put up was good. I don’t understand who you might be however certainly you’re going to a well-known blogger in the event you are not already ;) Cheers!

    Comment by Alanna Mcclenny — April 21, 2012 @ 11:52 am

  12. Bonjour, je suis un étudiant en genie logiciel en train de réaliser mon projet de fin d’étude, j’ai besoin d’ouvrir un terminal pour lancer des commandes mais franchement je suis débutant en IOS donc je veux un exemple bien détails pour comprendre comment il fonctionne. merci bien

    Comment by hammami sabri — February 15, 2013 @ 8:09 am

  13. With havin so much content do you ever run into any problems of plagorism or copyright infringement?
    My blog has a lot of exclusive content I’ve either authored myself or outsourced but it appears a lot of it is popping it up all over the web without my agreement. Do you know any methods to help stop content from being stolen? I’d definitely appreciate it.

    My webpage Best Free Cccam Server

    Comment by Best Free Cccam Server — April 9, 2013 @ 10:49 pm

  14. Hi there, I log on to your new stuff daily. Your story-telling style is awesome, keep
    doing what you’re doing!

    Comment by yahoo search — April 22, 2014 @ 10:34 am

  15. After looking into a few of the blog posts on your web page, I truly appreciate your technique
    of blogging. I added it to my bookmark website list and will be checking back in the near future.
    Take a look at my website as well and let me know how
    you feel.

    Feel free to visit my weblog: click

    Comment by click — July 8, 2014 @ 12:08 am

  16. Hello it’s me, I am also visiting this website daily, this
    site is genuinely pleasant and the viewers are actually sharing pleasant thoughts.

    Comment by Book of Ra Deluxe Online Free — July 24, 2014 @ 10:03 am

  17. I’m not that much of a internet reader to be honest but your blogs
    really nice, keep it up! I’ll go ahead and
    bookmark your website to come back later. All the best

    Comment by Book of Ra Symulator — July 27, 2014 @ 2:37 pm

  18. Understanding both advantages and disadvantages are important in order to choose the best internet
    marketing strategy. As the culture of internet slang grew, it
    took on new origins from pop culture or video games
    and television. It’s probably some mix of
    the two, so I have to give him props for not going too far in either direction.

    Comment by — October 21, 2014 @ 5:28 pm

  19. The teams can also reach out to the communities (one of
    the under-reported stories of the NBA lockout is how not having the association on their
    backs means fewer players will use their
    wealth and influence for community building) in order to build a fan base and generate connections with the team.
    Noosa and Noosa Heads are divided by the gorgeous Noosa Nationwide Park.
    I won’t lose a whole lot more bodyweight, but my
    skin will get tighter and thinner.

    Comment by free diamonds boom beach — December 28, 2014 @ 5:05 pm

  20. Thanks for your help

    Comment by Linksys Router Support Number — February 16, 2015 @ 3:53 pm

  21. I did it, but somehow its not working at my end.. What to do?

    Comment by Roma — February 24, 2015 @ 6:16 pm

  22. Hhhmmm.. I don’t know what’s wrong here.. it’s not working on my test server..

    Comment by Richa Shukla — February 24, 2015 @ 6:18 pm

  23. Welcome to Lucknow Richa Escorts Agency. Our helpful and polite receptionist are available Lucknow Escort in 24 hour till to assist you to find exactly the right girl for you……..

    Comment by Independent Escort in Lucknow — March 2, 2015 @ 5:17 pm

  24. Hi exceptional blog! Does running a blog similar to this take a
    lot of work? I have very little knowledge of coding but I
    was hoping to start my own blog in the near future. Anyways, if you have any suggestions or tips for new blog owners please share.
    I know this is off subject but I simply needed to ask.
    Thanks a lot!

    Comment by free cccam server 2015 — March 20, 2015 @ 4:51 pm

  25. Wonderful site you have here but I was curious if you knew of any user discussion forums that cover the same topics discussed in this article?
    I’d really like to be a part of community where I
    can get feedback from other experienced individuals that share the same interest.

    If you have any suggestions, please let me know. Many thanks!

    Comment by ask — March 26, 2015 @ 7:59 am

  26. Thanks for sharing such a wonderful information

    Comment by suzi — May 8, 2015 @ 5:26 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress