This post covers more common tasks when writing Swift scripts, following the post on an introduction to Swift scripting.


You can invoke shell to execute:

func shell(launchPath: String, arguments: [String]) -> String {
    let task = Process()
    task.launchPath = launchPath
    task.arguments = arguments
    let pipe = Pipe()
    task.standardOutput = pipe
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = String(data: data, encoding: .utf8)! as String
    return output

To use:

shell("/bin/pwd", arguments: [])
shell("/bin/cp", arguments: ["/path/to/file", "/path/to/another/file"])

Launch Arguments

Pass in launch arguments to your script with NSProcessInfo.

let arguments = ProcessInfo.processInfo.arguments as [String]
let dashedArguments = arguments.filter({$0.hasPrefix("-")})

for argument : String in dashedArguments {
    let index = argument.index(argument.startIndex, offsetBy: 1)
    let key = argument.substring(from: index)
    let value : Any? = UserDefaults.standard.value(forKey: key)

Note that the value is retrievable via NSUserDefaults

Example: ./main.swift -s 123 --mode godlike --nokill

Keys: s, -mode and -nokill
Values: 123 (integer), godlike (string) and nil




Back to Home