如何在Go中更改Shell的当前工作目录? [英] How to change the shell's current working directory in Go?

查看:73
本文介绍了如何在Go中更改Shell的当前工作目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Go, main.go 来实现 cd 命令:

  func main(){flag.Parse()如果flag.NArg()== 0 {curUser,err:= user.Current()如果err!= nil {log.Fatal(错误)}os.Chdir(curUser.HomeDir)//或像这样//cmd:= exec.Command("cd",curUser.HomeDir)fmt.Println(os.Getwd())//在应用程序中可以}} 

但是当我在shell中运行 go run main.go 时,它仍然不会切换到我的主目录.

那么如何通过运行go文件在shell中更改我的工作目录?

解决方案

您不能执行此操作;每个子进程都有从父进程继承的自己的工作目录.在这种情况下,您的 cd 从其父级(您的shell)获取其工作目录.子进程无法更改父进程的目录或任何其他状态.

这是基本的过程分离.允许子进程影响其父进程将遇到各种安全性和可用性问题.

Shell将 cd 实现为特殊内置".它不是外部二进制文件:

  $,其中cdcd:shell内置命令 

换句话说,当外壳程序运行 cd 命令时,它与外壳程序其余部分的运行过程相同.

shell的REPL的基本逻辑类似于:

<{行:= waitForInputLine()转变 {大小写字符串.HasPrefix(line,"cd"):os.chdir(strings.Split(line,")[1])//..检查其他内建函数和特殊情况./默认:runBinary(行)}}

无论使用哪种语言来实现,都无法在外部二进制文件中实现.

I want implement the cd command with Go, main.go:

func main() {
    flag.Parse()
    if flag.NArg() == 0 {
        curUser, err := user.Current()
        if err != nil {
            log.Fatal(err)
        }
        os.Chdir(curUser.HomeDir)
        // or like this
        // cmd := exec.Command("cd", curUser.HomeDir)
        fmt.Println(os.Getwd())   // ok in application
    }
}

But when I run go run main.go in shell, it still not switch to my home directory.

So how can I change my working directory in shell by running go files?

解决方案

You can't do this; every child process has its own working directory inherited from the parent. In this case, your cd gets its working directory from its parent (your shell). A child process can't change the directory – or any other state – of the parent process.

This is basic process separation. Allowing child processes to influence their parent would have all sorts of security and usability issues.

Shells implement cd as a "special builtin". It's not an external binary:

$ where cd
cd: shell built-in command

In other words, when the shell runs the cd command it's run in the same process as the rest of the shell.

The basic logic of a shell's REPL looks something like:

for {
    line := waitForInputLine()
    switch {
        case strings.HasPrefix(line, "cd"):
            os.chdir(strings.Split(line, " ")[1])

        // ..check other builtins and special cases./

        default:
            runBinary(line)
    }
}

There is no way you can implement that in an external binary, no matter which language you use to implement it.

这篇关于如何在Go中更改Shell的当前工作目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆