Skip to content

Instantly share code, notes, and snippets.

@backslash-f
Last active June 13, 2023 19:11
Show Gist options
  • Save backslash-f/02a25d10cbb8d8ff9038bf50728da162 to your computer and use it in GitHub Desktop.
Save backslash-f/02a25d10cbb8d8ff9038bf50728da162 to your computer and use it in GitHub Desktop.
Invoke Zsh commands via a Swift script
#!/usr/bin/swift
import Foundation
func shell(_ command: String) {
let task = Process()
task.launchPath = "/bin/zsh"
task.arguments = ["-c", command]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8) ?? ""
print(output)
}
shell("export MY_VAR=123 ; echo $MY_VAR")
// In CLI:
// chmod a+x Shell.swift
// ./Shell.swift
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment