Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa/ Objective-C Shell Command Line Execution

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.

like image 426
Tom Avatar asked Sep 25 '09 02:09

Tom


3 Answers

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.

like image 118
Quinn Taylor Avatar answered Oct 19 '22 00:10

Quinn Taylor


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.

like image 9
BJ Homer Avatar answered Oct 19 '22 01:10

BJ Homer


NSTask

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

like image 3
Terry Wilcox Avatar answered Oct 19 '22 00:10

Terry Wilcox