如何在 Swift 脚本中运行终端命令?(例如 xcodebuild)
问题描述:
我想用 swift 替换我的 CI bash 脚本.我不知道如何调用普通的终端命令,例如 ls
或 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 ....
答
如果您不在 Swift 代码中使用命令输出,以下就足够了:
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")
更新:适用于 Swift3/Xcode8
Updated: for Swift3/Xcode8