Compile Swift Logo

Using Process() to run terminal commands. Don't give up at the first sign of trouble

Season 4 Episode 22


This is the code I discuss in this episode for running a terminal command in a macOS GUI application.

let process = Process()
process.executableURL = URL(fileURLWithPath: gitPath.absoluteString)
process.currentDirectoryURL = URL(fileURLWithPath: savePath.absoluteString)
process.arguments = ["add", fileName.path]
let outPipe = Pipe()
let outFile = outPipe.fileHandleForReading
process.standardOutput = outPipe

do {
  try process.run()
    process.waitUntilExit()
    if #available(macOS 10.15.4, *) {
      if
        let data = try outFile.readToEnd(),
        let returnValue = String(data: data, encoding: .utf8) {
      }
      gitCommit()
    } else {
    // Fallback on earlier versions
    }
  } catch {
    print(error)
}

Copyright 2022 PeterWitham

Facebook Instagram Twitter Mastodon GitHub