欢迎使用 ShellOut,这是一个简单的包,使您可以轻松地从 Swift 脚本或命令行工具中“shell out(执行外部命令)”。
即使您可以使用原生 Swift 代码完成您需要的大部分任务,但有时您需要从脚本或工具中调用命令行,而这正是 ShellOut 使其变得如此简单的原因。
只需调用 shellOut()
,并指定您要运行的命令,以及您想要传递的任何参数。
let output = try shellOut(to: "echo", arguments: ["Hello world"])
print(output) // Hello world
您还可以轻松地一次运行一系列命令,可以选择在给定的路径下运行。
try shellOut(to: ["mkdir NewFolder", "echo \"Hello again\" > NewFolder/File"], at: "~/CurrentFolder")
let output = try shellOut(to: "cat File", at: "~/CurrentFolder/NewFolder")
print(output) // Hello again
如果发生错误,ShellOut 会自动读取 STDERR
并将其完美地格式化为类型化的 Swift 错误。
do {
try shellOut(to: "totally-invalid")
} catch {
let error = error as! ShellOutError
print(error.message) // Prints STDERR
print(error.output) // Prints STDOUT
}
使用 ShellOut 的另一种方法是执行预定义的命令,这使您可以轻松地执行常见任务,而无需使用字符串构建命令。 它还附带了一组用于常见任务(例如使用 Git、SPM 和操作文件系统)的此类预定义命令。
try shellOut(to: .gitInit())
try shellOut(to: .gitClone(url: repositoryURL))
try shellOut(to: .gitCommit(message: "A scripted commit!"))
try shellOut(to: .gitPush())
try shellOut(to: .gitPull(remote: "origin", branch: "release"))
try shellOut(to: .gitSubmoduleUpdate())
try shellOut(to: .gitCheckout(branch: "my-feature"))
try shellOut(to: .createFolder(named: "folder"))
try shellOut(to: .createFile(named: "file", contents: "Hello world"))
try shellOut(to: .moveFile(from: "path/a", to: "path/b"))
try shellOut(to: .copyFile(from: "path/a", to: "path/b"))
try shellOut(to: .openFile(at: "Project.xcodeproj"))
try shellOut(to: .readFile(at: "Podfile"))
try shellOut(to: .removeFile(from: "path/a"))
try shellOut(to: .createSymlink(to: "target", at: "link"))
try shellOut(to: .expandSymlink(at: "link"))
有关在 Swift 中处理文件和文件夹的更强大和面向对象的方式,请查看 Files
try shellOut(to: .createSwiftPackage(withType: .executable))
try shellOut(to: .updateSwiftPackages())
try shellOut(to: .generateSwiftPackageXcodeProject())
try shellOut(to: .buildSwiftPackage())
try shellOut(to: .testSwiftPackage())
在上面的列表中没有找到您想要的内容? 您可以使用 ShellOutCommand
轻松定义自己的命令。 如果您制作了一个您认为应该包含在内置命令中的命令,请随时在原始作者的存储库中 打开一个 PR。
Package.swift
文件的 dependencies
中.package(url: "https://github.com/Maxim-Lanskoy/ShellOut.git", .upToNextMajor(from: "2.4.0")