【问题标题】:osx swift pass path with space as argument to shell script called by NSTaskosx swift pass path with space 作为 NSTask 调用的 shell 脚本的参数
【发布时间】:2015-01-21 17:03:35
【问题描述】:

这是我无法使用的代码。如果我删除带有空格的目录部分,我的 shell 脚本运行良好。

shell 脚本简化为:/usr/bin/find $1 -name *.txt

空格错误是二元运算符预期的

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("doSimpleFind", ofType: "sh")

 let findTask = NSTask()
 let pipe = NSPipe()
 findTask.standardOutput = pipe

 // directory where to search from the script. testing the space in the name
 let constArgsString:String = "/Users/aUser/Library/Application\\ Support"
 //let constArgsString:String = "/Users/aUser/Library/"
 findTask.launchPath = path!
 findTask.arguments = [constArgsString]
 findTask.launch()
 findTask.waitUntilExit()
 let data = pipe.fileHandleForReading.readDataToEndOfFile()
 let outputText:String = NSString(data: data, encoding:NSUTF8StringEncoding)!
 cmdTextResult.textStorage?.mutableString.setString(outputText)

【问题讨论】:

  • 这种方法是我能够将参数从 NSTask 传递给 .sh 的唯一方法。我见过的所有其他示例都从参数启动命令。但无法将参数传递给 .sh 脚本

标签: macos shell swift nstask


【解决方案1】:

NSTask() 使用给定的参数“直接”启动进程,而不使用 shell。因此没有必要逃避任何 启动参数中的空格或其他字符:

let constArgsString = "/Users/aUser/Library/Application Support"

但是您必须正确处理 shell 脚本中带有空格的参数。在您的示例中,$1 需要用双引号引起来, 否则它可能会作为多个参数传递给find 命令:

/usr/bin/find "$1" -name "*.txt"

【讨论】:

  • 经过测试和工作。我在 "$@" 中尝试了 for c,但在路径中没有 "\" 的情况下没有尝试过。我很惊讶 find 命令以这种方式接受带有空格的路径,但很高兴它可以工作。试图重用一些旧脚本。
【解决方案2】:

为了使它完整,您应该获得如下文件夹路径:

let appSupportPath = FileManager.default.urls(for: .applicationSupportDirectory, inDomains: .UserDomainMask).first!.path

let libraryPath = FileManager.defaultManager.urls(for: .libraryDirectory, inDomains: .UserDomainMask).first!.path

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-02
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    相关资源
    最近更新 更多