Apple开发_运行Shell脚本代码

+ (NSString *)run_Shell:(NSString *)shell_path {
    //CHLog(@"脚本所在地址 ==> %@\n", script_path);
    if(shell_path) {
        NSTask *script_task = [[NSTask alloc] init];
        NSPipe *pipe = [NSPipe pipe];
        [script_task setStandardOutput:pipe];
        [script_task setStandardError:pipe];
        NSFileHandle *file_handle = [pipe fileHandleForReading];
        [script_task setLaunchPath:@"/bin/sh"];
        [script_task setArguments:@[shell_path]];
        [script_task launch];
        
        NSData *data = [file_handle readDataToEndOfFile];
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        CHLog (@"脚本运行情况 ==> %@", string);
        
        return string;
    }
    else {
        CHLog(@"脚本不存在,请检查!");
        return nil;
    }
}
  • 注意:运行脚本在app外部,可能运行提示无权限,具体原因不清楚。建议放在app沙盒内操作。
posted @ 2022-11-11 17:42  CH520  阅读(39)  评论(0编辑  收藏  举报