Created
May 1, 2020 05:40
-
-
Save kongzii/4b3bd3405a9fac979413e57696169848 to your computer and use it in GitHub Desktop.
Execute shell commands in Swift from String or Array
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
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