How to call a Unix program?

I want to call ls and capture its stdout output from my Swift program. How do I achieve that?

So, like the equivalent of system(…) in a C program?

I think you can use the Process class from Foundation.

This worked for me:

import Foundation

let p = Process()
p.executableURL = URL(fileURLWithPath: "/bin/ls")
let pipe = Pipe()
p.standardOutput = pipe
let data = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)!
1 Like

And for more examples of how to use it (or just a convenient package), see for example ShellOut, specifically this file


Thank you @Michael_Ilseman. That project is great for me to learn, specially with all of the documentation.