Skip to content

Instantly share code, notes, and snippets.

@kongzii
Created May 1, 2020 05:40
Show Gist options
  • Save kongzii/4b3bd3405a9fac979413e57696169848 to your computer and use it in GitHub Desktop.
Save kongzii/4b3bd3405a9fac979413e57696169848 to your computer and use it in GitHub Desktop.
Execute shell commands in Swift from String or Array
import Foundation
public extension Array where Element == String {
@discardableResult
func exec() -> String {
joined(separator: " ").exec()
}
}
public extension String {
static var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
@discardableResult
func exec() -> String {
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", self]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
return output
}
static func random(length: Int = 20) -> String {
var randomString = ""
for _ in 0 ..< length {
let randomValue = Int.random(in: 0 ..< String.alphabet.count)
randomString += "\(String.alphabet[String.alphabet.index(String.alphabet.startIndex, offsetBy: randomValue)])"
}
return randomString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment