用于执行shell命令,并轻松获取结果(数据,字符串和任何可解码)

ShellExecutor

用于执行 shell 命令,并轻松获取结果(数据、字符串和任何可解码)。

要求

  • Xcode 14.0+
  • 斯威夫特 5.7+
  • macOS 10.15+

安装

您可以通过SPM(Swift Package Manager)进行安装,通过Xcode添加,或者作为依赖项就像将其添加到依赖项值一样简单:ShellExecutorShellExecutorPackage.swift

...
dependencies: [
    .package(url: "https://github.com/azone/ShellExecutor.git", from: "0.1.0")
]
...

用法

ShellExecutor提供了许多执行 shell 命令的方法。

使用数组作为命令和参数:

let command: GeneralCommand = ["ipconfig", "getifaddr", "en0"]
do {
    let ip: String = try ShellExecutor.execute(command: command)
    print(ip) // it will be printed like 192.168.1.174
} catch {
    print(error)
}

执行多个命令,如管道

let command1: GeneralCommand = ["echo", "Hello"]
let command2: GeneralCommand = ["cat"]
do {
    let result: String = try ShellExecutor.execute(commands: [command1, command2])
    print(result) // will be print Hello
} catch {
    print(error)
}

Execute shell command directly

do {
    let ip: String = ShellExecutor.execute(shell: "ipconfig getifaddr en0") // and you can also specify which shell you want to use
    print(ip) // it will be printed like 192.168.1.174
} catch {
    print(error)
}

Other convenient ways to execute the commands

// decode struct from the command directly

struct Person: Decodable, Equatable {
    let name: String
    let age: Int
}

do {
    let jsonString = """
{ "name": "Logan", "age": 36 }
"""
    let command: GeneralCommand = ["echo", jsonString]
    let decoder = JSONDecoder()
    let person: Person = try ShellExecutor.execute(command: command, decoder: decoder)
    print(person) // Person(name: "Logan", age: 36)
} catch {
    print(error)
}

// execute shell command(s) using @resultBuilder
do {
    let ip: String = try ShellExecutor.execute {
        "ipconfig"
        "getifaddr"
        "en0"
    }
    print(ip) // 192.168.x.x
    
    let hello: String = try ShellExecutor.execute {
        ["echo", "Hello"]
        ["cat"]
    }
    print(hello) // Hello
} catch {
    print(error)
}

For more information & examples please see the tests.

LICENSE


for details.

GitHub

点击跳转