18

This is probably a stupid question, but how can I execute a shell command from my Cocoa app?

I have the command as a string "command", but can easily manipulate data as needed.

There is no need to get a returned output value.

Tom
  • 6,947
  • 7
  • 46
  • 76
  • 1
    possible duplicate of [Execute a terminal command from a Cocoa app](http://stackoverflow.com/questions/412562/execute-a-terminal-command-from-a-cocoa-app) – outis Jun 23 '12 at 20:01
  • 1
    also see this question: http://stackoverflow.com/questions/412562/execute-a-terminal-command-from-a-cocoa-app/696942#696942 – kent Sep 25 '09 at 12:40

3 Answers3

30

NSTask is pretty easy to do this with. For a synchronous call, you can use something like this fragment:

NSString *path = @"/path/to/executable";
NSArray *args = [NSArray arrayWithObjects:..., nil];
[[NSTask launchedTaskWithLaunchPath:path arguments:args] waitUntilExit];

The -waitUntilExit call makes sure it finishes before proceeding. If the task can be asynchronous, you can remove that call and just let the NSTask do it's thing.

Quinn Taylor
  • 44,553
  • 16
  • 113
  • 131
9

If you just want to run something and don't care about the output or return code (for example, you want to touch a file), you can just do

system("touch myfile.txt");

Easy as that.

BJ Homer
  • 48,806
  • 11
  • 116
  • 129
  • 9
    Be very, very careful with `system` and `popen`. It's easy to introduce a vulnerability by letting characters through to the shell that it will consider special. NSTask and `fork`/`exec` are much safer. – Peter Hosey Sep 25 '09 at 03:29
3

NSTask

Using the NSTask class, your program can run another program as a subprocess and can monitor that program’s execution.

Terry Wilcox
  • 9,010
  • 1
  • 34
  • 36