如何在Swift脚本中运行终端命令?(例如xcodebuild) [英] How do I run a terminal command in a Swift script? (e.g. xcodebuild)

查看:61
本文介绍了如何在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

这篇关于如何在Swift脚本中运行终端命令?(例如xcodebuild)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆