使用NSTask运行shell脚本会导致posix_spawn错误

cod*_*ryn 11 macos shell posix objective-c nstask

我正在尝试使用以下代码运行带有NSTask的shell脚本:

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/Users/username/connect.sh"];
[task launch];
Run Code Online (Sandbox Code Playgroud)

但我得到An uncaught exception was raisedCouldn't posix_spawn: error 8

如果我只是在终端中运行脚本,一切正常.

以下是脚本包含的内容:

if [ ! -d ~/Remote/username/projects  ] 
then  
        sshfs -C -p 22 user@remotecomputer.com:/home/username ~/Remote/username        
fi
Run Code Online (Sandbox Code Playgroud)

pla*_*mik 8

您还可以添加#!/bin/bash到脚本的开头:

#!/bin/bash

if [ ! -d ~/Remote/username/projects  ] 
then  
    sshfs -C -p 22 user@remotecomputer.com:/home/username        ~/Remote/username        
fi
Run Code Online (Sandbox Code Playgroud)


l'L*_*L'l 3

您需要像这样使用 setLaunchPath:

[task setLaunchPath:@"/bin/sh"];
Run Code Online (Sandbox Code Playgroud)

然后为您的脚本使用 setArguments:

[task setArguments: [NSArray arrayWithObjects: @"~/connect.sh", nil]];
Run Code Online (Sandbox Code Playgroud)