objective_c调用shell脚本可以很方便地提升代码效率。下面是调用shell脚本并将shell脚本运行的结果返回的例子,调用该函数时,只需把shell脚本的路径传进来即可。亲测通过
-(id) InvokingShellScriptAtPath :(NSString*) shellScriptPath
{NSTask *shellTask = [[NSTask alloc]init];
[shellTask setLaunchPath:@"/bin/sh"];
NSString *shellStr = [NSString stringWithFormat:@"sh %@",shellScriptPath];
//-c 表示将后面的内容当成shellcode来执行
NSPipe *pipe = [[NSPipe alloc]init];
[shellTask setStandardOutput:pipe];
[shellTask launch];
NSFileHandle *file = [pipe fileHandleForReading];
NSData *data =[file readDataToEndOfFile];
NSString *strReturnFromShell = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"The return content from shell script is: %@",strReturnFromShell);
return strReturnFromShell;
}