osx swift传递路径,空格作为NSTask调用的shell脚本的参数

时间:2015-01-21 17:03:35

标签: macos shell swift nstask

这是我无法工作的代码。如果我用空格删除目录部分,我的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)

2 个答案:

答案 0 :(得分:3)

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

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

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

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

答案 1 :(得分:1)

为了使其完整,您应该获取文件夹路径,如下所示:

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

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