objective-c - NSTask 没有从用户环境中获取 $PATH

标签 objective-c cocoa bash shell nstask

我不知道为什么这个方法返回一个空字符串:

- (NSString *)installedGitLocation {
    NSString *launchPath = @"/usr/bin/which";

    // Set up the task
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:launchPath];
    NSArray *args = [NSArray arrayWithObject:@"git"];
    [task setArguments:args];

    // Set the output pipe.
    NSPipe *outPipe = [[NSPipe alloc] init];
    [task setStandardOutput:outPipe];

    [task launch];

    NSData *data = [[outPipe fileHandleForReading] readDataToEndOfFile];
    NSString *path = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    return path;
}

如果不是传递 @"git" 作为参数,而是传递 @"which" 我得到 /usr/bin/which按预期返回。所以至少这个原则是有效的。

从终端

$ which which
$ /usr/bin/which
$
$ which git
$ /usr/local/git/bin/git

所以它在那里工作。

我唯一能想到的是 which 没有搜索我环境中的所有路径。

这让我发疯!有人有什么想法吗?

编辑:看起来这是关于设置 NSTask 或用户的 shell(例如,~/.bashrc),以便 NSTask 看到正确的环境($PATH)。

最佳答案

尝试,

    [task setLaunchPath:@"/bin/bash"];
    NSArray *args = [NSArray arrayWithObjects:@"-l",
                     @"-c",
                     @"which git",
                     nil];
    [task setArguments: args];

这对我在 Snow Leopard 上很有效;我没有在任何其他系统上测试过。 -l(小写的 L)告诉 bash “就像它被调用为登录 shell 一样”,并且在这个过程中它选择了我的正常 $PATH。如果启动路径设置为/bit/sh,这对我不起作用,即使使用 -l。

关于objective-c - NSTask 没有从用户环境中获取 $PATH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/386783/

相关文章:

linux - 无法在 bash Linux 中为整数赋值

ios - NSDateFormatter dateFromString在iOS 10上运行但在iOS 11上返回nil

c++ - 将 std 字符串转换为 nsstring

objective-c - 仅调用方法的一部分

objective-c - 如何使 NSComboBox 不可见或透明

cocoa - 子类化/扩展 NSMutabelSet?

bash - 仅更改一条管道的 Jenkins shell

iphone - 文本字段覆盖有背景,就像 Clear iPhone 应用程序一样

ios - 显示动画并锁定当前 View

bash - 使用标准 Linux 命令行工具修改二进制文件中的字节