Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

RevK

macrumors member
Original poster
Apr 26, 2004
65
0
Hello MacRumors;

I have been working on a few projects in Objective-C recently and have found it extremely difficult (if not impossible) to run a shell command/script from the code.

I have found this code for running a shell script from the resources folder:
Code:
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/sh"];
[task setArguments:[NSArray arrayWithObjects:[[NSBundle mainBundle] pathForResource:@"sscript" ofType:@"sh"], nil]];
[task launch];

The only thing is that I'd like to be able to use type the command right into the code; for example:

touch /Users/myusername/Desktop test.txt

Any help would be greatly appreciated, Thanks!
 
Hello MacRumors;

I have been working on a few projects in Objective-C recently and have found it extremely difficult (if not impossible) to run a shell command/script from the code.

I have found this code for running a shell script from the resources folder:
Code:
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/sh"];
[task setArguments:[NSArray arrayWithObjects:[[NSBundle mainBundle] pathForResource:@"sscript" ofType:@"sh"], nil]];
[task launch];

The only thing is that I'd like to be able to use type the command right into the code; for example:

touch /Users/myusername/Desktop test.txt

Any help would be greatly appreciated, Thanks!

Easy. Save the script to a temporary file and run that, or (I don't recall if sh/bash accepted input from stdin) pipe to stdin.
 
Would saving to a temporary file be as efficient as using system()?

I've heard bad things about using system().

Would way would be best for some simple commands?
 
From another forum post I found:


"You could use system() but it's use is proscribed.

NSTask would be the proper API supported method of doing it."

From the system() man page:
Code:
STANDARDS
     The system() function conforms to ISO/IEC 9899:1990 (``ISO C90'') and is
     expected to be IEEE Std 1003.2 (``POSIX.2'') compatible.

I'm more confident in that staying the same than NSTask.

-Lee
 
I tried using system() in a test project and it works great!

Thanks for showing me. You all are really awesome.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.