MEG4WATZ
MEG4WATZ

Reputation: 13

How can i run a shell script with administrator privileges within SwiftUI using osascript

I’m trying to make a simple macOS App which runs a shell script with administrator privileges when a specific button is pressed. To run the shell script in terminal i successfully tested this command:

osascript -e 'do shell script "/Users/andreas/checkertool.sh" with administrator privileges'

Unfortunately i'm not able to execute this command when pressing the button. Following error message appears:

0:2: execution error: The variable „do“ is not defined. (-2753)

This is what my code looks like so far. Any help would be highly appreciated!

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()
    }
}

Upvotes: 1

Views: 2295

Answers (1)

Asperi
Asperi

Reputation: 258413

The correct terminal command should be as (if you use specific shell inside script then sh should be replaced correspondingly, say bash)

$ osascript -e 'do shell script "sh /Users/andreas/checkertool.sh" with administrator privileges'

so your arguments should be as follow:

process.arguments = ["-e", "do shell script \"sh /Users/andreas/checkertool.sh\" with administrator privileges"]

P.S. assuming you do this w/o sandbox, because I have doubts it would allow this.

Upvotes: 1

Related Questions