【问题标题】:Swift Process - execute command errorSwift Process - 执行命令错误
【发布时间】:2017-04-06 22:29:31
【问题描述】:

我正在尝试从一个用 Swift 编写的 Mac App 执行“历史”命令。

@discardableResult
func shell(_ args: String...) -> Int32 {
    let task = Process()
    task.launchPath = "/bin/bash"
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

shell("history")

它总是返回这个错误:

env: history: No such file or directory

怎么了?真的可以使用 Mac 应用程序中的用户命令行历史记录吗?

【问题讨论】:

    标签: swift bash macos terminal


    【解决方案1】:

    将某些内置的GNU 命令与NSTask 一起使用(与history 一样被视为“交互式”)通常需要设置环境变量以便shell 知道要返回什么,例如:

    private let env = NSProcessInfo.processInfo().environment
    

    这可能很困难,因为显然并非所有用户都使用相同的环境变量或 shell。另一种方法是在 NSTask 中使用不需要获取/设置环境的 bash 命令:

    let task = Process()
    task.launchPath = "/bin/bash"
    task.arguments = ["-c", "cat -n ${HOME}/.bash_history"]
    
    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()
    
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
    
    print(output!)
    

    生成的输出应该类似于实际 shell 历史记录的编号格式。

    【讨论】:

    • 在同一个脚本中,如何导出日期? "export HISTTIMEFORMAT=\'%m/%d - %H:%M:%S:\'" 给我同样的回报'没有这样的文件或目录'
    【解决方案2】:

    history 命令是一个内部 bash 命令。因此,正确的语法是:

    $ bash -C history
    

    在您的shell 函数中:

    task.arguments = ["-C"] + args
    

    【讨论】:

    • @Marco 有一个错字...请现在再试一次。
    猜你喜欢
    • 2021-12-10
    • 2021-07-28
    • 1970-01-01
    • 2015-09-03
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多