How do I pipe to a swift command line tool?

I have a command line tool and I want to perform something similar as

ls | mycommandlinetool

piping the result from ls to mycommandlinetool

I'd need help to: find either a tutorial, or how to write the code.

If the input isn't very big, that's the easiest solution I can think of.

import Foundation

let input = FileHandle.standardInput

if let text = String(bytes: input.availableData, encoding: .utf8) {
  print(text)
}
5 Likes

You can use the readLine global function to read from standard input.

https://developer.apple.com/documentation/swift/1641199-readline

4 Likes

As of my need now, the chained tool is faster than the primary tool, so it will solve the problem.

But I also had in mind to manufacture more tools and it might be handy to know how to handle when you need to control the input when the chained tool is slower. (or when input is very big)