Pichingo
Pichingo

Reputation: 57

Run Shell Script from Xcode button

I'm trying to get a button in Xcode to run a shell script with clicked.

This works

@IBAction func test(_ sender: NSButton) {
        let path = "/usr/bin/say"
        let arguments = ["hello world"]     
        sender.isEnabled = false
        let task = Process.launchedProcess(launchPath: path, arguments: arguments)
        task.waitUntilExit()
        sender.isEnabled = true
    }

But when I try this it does not work to run a script from the Desktop

@IBAction func test(_ sender: NSButton) {
     let path = "/bin/bash"
     let arguments = ["~/Desktop/test.sh"]      
     sender.isEnabled = false
     let task = Process.launchedProcess(launchPath: path, arguments: arguments)
     task.waitUntilExit()     
     sender.isEnabled = true
 }

I get this error output in Xcode

/bin/bash: ~/Desktop/test.sh: No such file or directory

If anyone can help me with some help or example that would great. Thank you.

Upvotes: 0

Views: 7525

Answers (2)

sudarshan Mane
sudarshan Mane

Reputation: 31

  func shell(_ args: String) -> String {
    var outstr = ""
    let task = Process()
    task.launchPath = "/bin/sh"
    task.arguments = ["-c", args]
    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    if let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
        outstr = output as String
    }
    task.waitUntilExit()
    return outstr
}

This Function returns output of Bash Script you're trying to run

 let cmd = "for i in $(ifconfig -lu); do if ifconfig $i | grep -q \"status: active\" ; then echo $i; fi; done"

Above Code Demonstrate how to use it.

Upvotes: 1

Lara Maia
Lara Maia

Reputation: 134

Turn off Xcode sandbox mode, it will fix the issue

Upvotes: 2

Related Questions