swiftbashshellxcodebuild

How do I run a terminal command in a Swift script? (e.g. xcodebuild)


I want to replace my CI bash scripts with swift. I can't figure out how to invoke normal terminal command such as ls or xcodebuild

#!/usr/bin/env xcrun swift

import Foundation // Works
println("Test") // Works
ls // Fails
xcodebuild -workspace myApp.xcworkspace // Fails

$ ./script.swift
./script.swift:5:1: error: use of unresolved identifier 'ls'
ls // Fails
^
... etc ....

Solution

  • If you don't use command outputs in Swift code, following would be sufficient:

    #!/usr/bin/env swift
    
    import Foundation
    
    @discardableResult
    func shell(_ args: String...) -> Int32 {
        let task = Process()
        task.launchPath = "/usr/bin/env"
        task.arguments = args
        task.launch()
        task.waitUntilExit()
        return task.terminationStatus
    }
    
    shell("ls")
    shell("xcodebuild", "-workspace", "myApp.xcworkspace")
    

    Updated: for Swift3/Xcode8