How to access the Terminal's $PATH variable from within my mac app, it seems to uses a different $PATH

前端 未结 1 826
萌比男神i
萌比男神i 2021-02-06 10:47

I\'m trying to make a mac app where the user can type in commands just like they would in the mac terminal, I got most of it working however I found out that the $PATH variable

1条回答
  •  既然无缘
    2021-02-06 11:32

    Adding bash Shell Path

    The default shell paths can be found in /etc/paths and /etc/path.d/. One way to read the shell paths is to use the path_helper command. Extending the code example above and using bash as the shell:

    let taskShell = Process()
    var envShell = ProcessInfo.processInfo.environment
    taskShell.launchPath = "/usr/bin/env"
    taskShell.arguments = ["/bin/bash","-c","eval $(/usr/libexec/path_helper -s) ; echo $PATH"]
    let pipeShell = Pipe()
    taskShell.standardOutput = pipeShell
    taskShell.standardError = pipeShell
    taskShell.launch()
    taskShell.waitUntilExit()
    let dataShell = pipeShell.fileHandleForReading.readDataToEndOfFile()
    var outputShell: String = NSString(data: dataShell, encoding: String.Encoding.utf8.rawValue) as! String
    outputShell = outputShell.replacingOccurrences(of: "\n", with: "", options: .literal, range: nil)
    print(outputShell)
    
    let task = Process()
    var env = ProcessInfo.processInfo.environment
    var path = env["PATH"]! as String
    path = outputShell + ":" + path
    env["PATH"] = path
    task.environment = env
    task.launchPath = "/usr/bin/env"
    task.arguments = ["/bin/bash", "-c", "echo $PATH"]
    let pipe = Pipe()
    task.standardOutput = pipe
    task.standardError = pipe
    task.launch()
    task.waitUntilExit()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    var output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
    output = output.replacingOccurrences(of: "\n", with: "", options: .literal, range: nil)
    print(output)
    

    Note:

    1. This code example calls the shell in non-interactive mode. This means that it won't execute any user specific profiles; such as /Users/*userid*/.bash_profile.
    2. The paths can be listed multiple times in the PATH environment variable. They will be traversed from left to right.

    References

    There are a couple of threads on application and shell PATH's for OS X which provide more context How to set system wide environment variables on OS X Mavericks and Setting the system wide path environment variable in mavericks

    0 讨论(0)
提交回复
热议问题