Objective-C(cocoa)运行shell脚本,得到返回值


NSArray*Array = [[NSArray alloc] init];
Array = [NSBundle pathsForResourcesOfType:@"sh" inDirectory:[[NSBundle mainBundle]resourcePath]];
NSLog(@"%@", Array);
NSString* scriptPath = [[NSBundle mainBundle] pathForResource:@"hello" ofType:@"sh"];
NSLog(@"%@", scriptPath);
if(scriptPath){
NSArray* theArguments = [NSArray arrayWithObjects: @"/bin/sh", scriptPath, theName,nil];
NSTask* scriptTask = [[NSTask alloc] init];
NSPipe *pipe;
pipe = [NSPipe pipe];
[scriptTask setStandardOutput: pipe];
[scriptTask setStandardError: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[scriptTask setLaunchPath: [theArguments objectAtIndex:0]];
[scriptTask setArguments: [theArguments subarrayWithRange: NSMakeRange (1,([theArguments count] - 1))]];
[scriptTask launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"got\n%@", string);
} else {
NSLog(@"That dosn't exist");
}

你可能感兴趣的:(shell,Objective-C)