osx swift 将路径 space 作为参数传递给 NSTask 调用的 shell 脚本
osx swift pass path with space as argument to shell script called by NSTask
这是我无法开始工作的代码。如果我用 space 删除目录部分,我的 shell 脚本运行正常。
shell 脚本简化为:/usr/bin/find $1 -name *.txt
错误 space 是预期的二元运算符
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()
使用给定的参数启动进程 "directly",而不使用 shell。因此没有必要逃避任何
space 或启动参数中的其他字符:
let constArgsString = "/Users/aUser/Library/Application Support"
但是您必须在 shell 脚本中正确处理带有 space 的参数。在您的示例中,</code> 需要用双引号引起来,
否则它可能作为多个参数传递给 <code>find
命令:
/usr/bin/find "" -name "*.txt"
为了使其完整,您应该获取如下文件夹路径:
let appSupportPath = FileManager.default.urls(for: .applicationSupportDirectory, inDomains: .UserDomainMask).first!.path
或
let libraryPath = FileManager.defaultManager.urls(for: .libraryDirectory, inDomains: .UserDomainMask).first!.path
这是我无法开始工作的代码。如果我用 space 删除目录部分,我的 shell 脚本运行正常。
shell 脚本简化为:/usr/bin/find $1 -name *.txt
错误 space 是预期的二元运算符
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()
使用给定的参数启动进程 "directly",而不使用 shell。因此没有必要逃避任何
space 或启动参数中的其他字符:
let constArgsString = "/Users/aUser/Library/Application Support"
但是您必须在 shell 脚本中正确处理带有 space 的参数。在您的示例中,</code> 需要用双引号引起来,
否则它可能作为多个参数传递给 <code>find
命令:
/usr/bin/find "" -name "*.txt"
为了使其完整,您应该获取如下文件夹路径:
let appSupportPath = FileManager.default.urls(for: .applicationSupportDirectory, inDomains: .UserDomainMask).first!.path
或
let libraryPath = FileManager.defaultManager.urls(for: .libraryDirectory, inDomains: .UserDomainMask).first!.path