gpt4 book ai didi

macos - osx 快速传递路径,空格作为 NSTask 调用的 shell 脚本的参数

转载 作者:搜寻专家 更新时间:2023-11-01 06:23:48 25 4
gpt4 key购买 nike

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

关于macos - osx 快速传递路径,空格作为 NSTask 调用的 shell 脚本的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28072818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com