Skip to content

Instantly share code, notes, and snippets.

@jbadger3
Created November 29, 2022 22:54
Show Gist options
  • Save jbadger3/54aa228b48b714a1d06a5059984c4bfe to your computer and use it in GitHub Desktop.
Save jbadger3/54aa228b48b714a1d06a5059984c4bfe to your computer and use it in GitHub Desktop.
Example of piping together commands in swift.
#!/usr/bin/swift
import Foundation
let catProcess = Process()
catProcess.executableURL = URL(fileURLWithPath: "/bin/cat")
catProcess.arguments = ["PipeExample.swift"]
let pipe1 = Pipe()
let grepProcess = Process()
grepProcess.executableURL = URL(fileURLWithPath: "/usr/bin/grep")
grepProcess.arguments = ["-n", "pipe2"]
catProcess.standardOutput = pipe1
grepProcess.standardInput = pipe1
let pipe2 = Pipe()
grepProcess.standardOutput = pipe2
pipe2.fileHandleForReading.readabilityHandler = { fileHandle in
let data = fileHandle.availableData
if data.isEmpty { // EOF
pipe2.fileHandleForReading.readabilityHandler = nil
return
}
print(String(data: data, encoding: .utf8)!)
}
try catProcess.run()
try grepProcess.run()
grepProcess.waitUntilExit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment