Search code examples
swiftterminalzshmacos-big-sur

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!


Solution

  • There is a deprecated property currentDirectoryPath on Process.

    On the assumption you won't want to use a deprecated property, after reading its documentation head over to the FileManager and look at is provisions for managing the current directory and their implications.

    Or just use cd as you've considered – you are launching a shell (zsh) with a shell command line as an argument. A command line can contain multiple commands separated by semicolons so you can prepend a cd to your command value.

    The latter approach avoids changing your current process' current directory.

    HTH