我正在尝试制作一个简单的 macOS 应用程序,当按下特定按钮时,它会以管理员权限运行 shell 脚本。为了在终端中运行 shell 脚本,我成功测试了此命令:
osascript -e '使用管理员权限执行 shell 脚本“/Users/andreas/checkertool.sh”'
不幸的是,按下按钮时我无法执行此命令。出现以下错误消息:
0:2:执行错误:变量“do”未定义。 (-2753)
这就是我的代码到目前为止的样子。任何帮助将不胜感激!
import SwiftUI
struct ContentView: View {
@State var script = "/Users/andreas/checkertool.sh"
@State var isRunning = false
var body: some View {
VStack {
Text("Checker Tool")
.font(.largeTitle)
.padding()
HStack {
Button(action: {
let process = Process()
process.launchPath = "/usr/bin/osascript"
process.arguments = ["-e", "do", "shell script", "/Users/andreas/checkertool.sh", "with administrator privileges"]
process.launch()
process.waitUntilExit()
}) {
Text("Check")
}.disabled(isRunning)
.padding(.trailing)
}
}.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
最佳答案
正确的终端命令应该是(如果您在脚本中使用特定的 shell,则应相应地替换 sh
,例如 bash
)
$ osascript -e 'do shell script "sh /Users/andreas/checkertool.sh" with administrator privileges'
所以你的论点应该如下:
process.arguments = ["-e", "do shell script \"sh /Users/andreas/checkertool.sh\" with administrator privileges"]
附注假设您在没有沙箱的情况下执行此操作,因为我怀疑它是否允许这样做。
关于xcode - 如何使用 osascript 在 SwiftUI 中以管理员权限运行 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59554711/