11

How can I call an external command (launch a subprocess) from a Swift script?

Perhaps something like call(["ls", "-l"]) in Python.

RyanM
  • 4,474
  • 4
  • 37
  • 44

1 Answers1

19

You can still use NSTask in Swift. Your example would be something like this.

let task = NSTask()
task.launchPath = "/bin/ls"
task.arguments = ["-l"]
task.launch()

Swift 3+, macOS 10.13+

let task = Process()
task.executableURL = URL(fileURLWithPath: "/bin/ls")
task.arguments = ["-l"]
task.run()
Linus Unnebäck
  • 23,234
  • 15
  • 74
  • 89
Connor Pearson
  • 63,902
  • 28
  • 145
  • 142