Created
November 29, 2022 22:54
-
-
Save jbadger3/54aa228b48b714a1d06a5059984c4bfe to your computer and use it in GitHub Desktop.
Example of piping together commands in swift.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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