首页 > 解决方案 > How to run terminal command in swift from any directory?

问题描述

I'm trying to creating a macOS application that that involves allowing the user to run terminal commands. I am able to run a command, but it runs from a directory inside my app, as far as I can tell. Running pwd returns /Users/<me>/Library/Containers/<My app's bundle identifier>/Data.

How can I chose what directory the command runs from?

I'm also looking for a way to get cd to work, but if I can chose what directory to run the terminal command from, I can handle cd manually.

Here is the code that I'm currently using to run terminal commands:

func shell(_ command: String) -> String {
    let task = Process()
    let pipe = Pipe()

    task.standardOutput = pipe
    task.arguments = ["-c", command]
    task.launchPath = "/bin/zsh"
    task.launch()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = String(data: data, encoding: .utf8)!

    return output
    
}

I'm using Xcode 12 on Big Sur.

Thanks!

标签: swiftterminalzshmacos-big-sur

解决方案


上有一个已弃用的属性 currentDirectoryPathProcess

假设您不想使用已弃用的属性,请在阅读其文档后转到FileManager并查看管理当前目录及其含义的规定。

或者只是cd按照您的考虑使用 - 您正在启动一个zsh带有shell 命令行作为参数的 shell ( )。命令行可以包含多个用分号分隔的命令,因此您可以将 acd添加到您的command值中。

后一种方法避免更改当前进程的当前目录。

高温高压


推荐阅读