这是我无法工作的代码。如果我删除带有空间的目录部分,我的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()
使用给定的参数“直接”启动进程,而不使用shell。因此,没有必要在启动参数中转义任何空格或其他字符:
let constArgsString = "/Users/aUser/Library/Application Support"
但是你必须正确处理shell脚本中带空格的参数。在您的示例中,$1
需要用双引号括起来,否则它可能作为多个参数传递给find
命令:
/usr/bin/find "$1" -name "*.txt"
只是为了完成它你应该获得文件夹路径如下:
let appSupportPath = FileManager.default.urls(for: .applicationSupportDirectory, inDomains: .UserDomainMask).first!.path
要么
let libraryPath = FileManager.defaultManager.urls(for: .libraryDirectory, inDomains: .UserDomainMask).first!.path