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!
 

Catfish_Man

macrumors 68030
Sep 13, 2001
2,579
2
Portland, OR
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.
 

RevK

macrumors member
Original poster
Apr 26, 2004
65
0
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?
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
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
 

RevK

macrumors member
Original poster
Apr 26, 2004
65
0
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.