英文:
Golang: Chdir and stay there on program termination
问题
在golang(以及bash脚本)中,如果我改变当前工作目录(使用os.Chdir),它会起作用,但是当程序终止时,工作目录会被重置为程序启动时的位置。
这是有道理的,但是我想做的是一个智能磁盘导航器(类似于我们旧时钟爱的ncd,“Norton Change Directory”)。
我如何告诉二进制文件(或启动它的shell,或其他什么)不要重置为先前的工作路径?
我希望完全通过Go二进制文件实现这一点,而不是修改.bashrc或.zshrc(以实现可移植性)。
英文:
In golang (as well as bash scripting) if I change the current working directory (with os.Chdir) it works, but when the program terminates the working directory gets reset to the location it had when the program started.
It makes sense, but what I want to do is an inteligent disk navigator (something like our old and beloved ncd, "Norton Change Directory").
How can I tell the binary (or the shell that starts it, or whatever) not to reset to the previous working path?
I would like to achieve that entirely from within the Go binary, without modifying .bashrc or .zshrc (for portability)
答案1
得分: 10
每个进程的工作目录都是进程私有的。
要实现这一点,您需要跳过循环。例如,您的程序可以编写一个脚本(文件),稍后可以从脚本中调用您的程序,在您的程序终止后执行。
另一种不太破解的方法是:
$ cd $(prog)
其中prog将新的工作目录写入stdout。
英文:
The working directory of every process is process-private.
You'll have to jump loops to achieve this. For example, your program can write a script (file), which can be executed later, after you program terminates, from a script, which invoked your program.
Another, less hacky method is:
$ cd $(prog)
where prog writes the new wd to stdout.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论