Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running shell commands in Swift

I'm trying to run shell commands using Swift in my OSX app.

Running basic commands such as echo work fine but the following throws

"env: node: No such file or directory"

@IBAction func streamTorrent(sender: AnyObject) {
  shell("node", "-v")
}

func shell(args: String...) -> Int32 {
    let task = NSTask()
    task.launchPath = "/usr/bin/env"
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

I also get "sh: node: command not found" when running the system command.

system("node -v")

Update:

Not as nice as some of the suggestions below, but I managed to echo the command into a file and have it opened and executed in terminal:

system("echo node -v > ~/installation.command; chmod +x ~/installation.command; open ~/installation.command")
like image 571
Adam Bishti Avatar asked Aug 26 '15 23:08

Adam Bishti


People also ask

How do I run a command in Xcode?

go to the 'Info' tab and in a menu 'Executable' choose 'Other...' in file window go to search input field and type 'terminal' and click on its icon when you find it. Now you should see 'Terminal. app' in 'Executable' field.

What is $() in Shell?

$() – the command substitution. ${} – the parameter substitution/variable expansion.


1 Answers

func shell(command: String) -> Int32 {
    let task = NSTask()
    task.launchPath = "/usr/bin/env"
    task.arguments = ["bash", "-c", command]
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

So you can do shell("node -v") which I find more convenient:

like image 81
ReDetection Avatar answered Sep 22 '22 12:09

ReDetection