Search code examples
objective-cosx-elcapitan

NSTask code, using objectivec, to get command line output no longer working in El Capitan


The following code previously worked fine in OS X Yosemite, but now it usually does not work in OS X El Capitan, usually returning an empty string, for output.

- (NSString*)runCommandLine:(NSString*)executable withArgs:(NSString*)arg {
    NSTask *commandLine = [[NSTask alloc] init];
    [commandLine setLaunchPath: executable];
    NSLog(@"CL EXECUTABLE: %@",executable);

    NSArray *arguments = [NSArray arrayWithObjects: arg, nil];
    [commandLine setArguments: arguments];
    NSLog(@"CL ARGUMENTS: %@",arguments);

    NSPipe *pipe = [NSPipe pipe];
    [commandLine setStandardOutput: pipe];  
    NSFileHandle *file = [pipe fileHandleForReading];    
    [commandLine launch];
    [commandLine waitUntilExit];

    NSData *data = [file readDataToEndOfFile];
    NSString *output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    NSLog(@"CL OUTPUT: %@",output);
    return output;
}

I then call it using the following example. There is no error, output is simple "" and the terminationstatus is 1:

NSString *adbLocation = [self runCommandLine:@"/usr/bin/which" withArgs: @"adb"];

This example for ls works fine (termination status is 0).

NSString *lsOutput = [[self runCommandLine:@"/usr/local/opt/coreutils/libexec/gnubin/ls" withArgs: @"-la"];

Thanks in advance for the suggestions!


Solution

  • Thanks Ken for sending me in the right direction.

    I solved this by doing: NSString *executable = @"/bin/bash"

    And for my example case of which adb:

    NSArray *arguments = [NSArray arrayWithObjects: @"-l",@"-c",@"which adb",nil];