问题描述
我想用C编写一个命令行工具,充当可移植到Windows/Mac/Linux的高级"cd"或"pushd/popd"命令. (有关详细信息,以防万一,请访问 http://alsweigart .tumblr.com/post/4008393181/command-line-idea-up )
I'd like to write a command line tool in C that acts as an advanced "cd" or "pushd/popd" command that can be ported to Windows/Mac/Linux. (Full details, in case you are curious, are at http://alsweigart.tumblr.com/post/4008393181/command-line-idea-up )
问题是,当用户从shell运行程序时,更改当前工作目录将更改程序的cwd,而不是shell的cwd.
The problem is, when the user runs a program from the shell, changing the current working directory will change the program's cwd, instead of the shell's cwd.
有没有一种方法可以编写程序来完成我想做的事情,还是我不得不诉诸bash脚本/批处理文件?
Is there a way to write a program to do what I want, or will I have to resort to writing bash scripts/batch files?
或者,有什么方法可以通过管道将程序的输出作为shell命令运行吗?即,程序输出"cd/foo/bar",shell脚本调用该程序并将其输出作为shell命令运行.
Alternatively, is there a way I could pipe the output of a program to be run as a shell command? i.e. The program outputs "cd /foo/bar" and a shell script calls this program and runs its output as a shell command.
推荐答案
通常,一个进程不能更改另一个进程的当前目录(在Windows和Unix系统上都是如此).因此,在外壳程序外部作为单独进程运行的程序无法更改外壳程序的当前目录.
In general, one process can't change the current directory of another process (this is true on both Windows and Unix systems). Therefore, a program that runs as a separate process outside a shell can't change the current directory of the shell.
您可能必须使用批处理文件和/或Shell脚本的某种组合来完成您想做的事情.请注意,尽管Windows批处理文件可以更改运行它们的Shell的当前目录,但对于Unix上的Shell脚本来说,不是.对于Unix,您可能要使用外壳功能,它们可以在同一进程中运行.请注意,编写shell函数是特定于shell的,因此您也必须将程序移植到要支持的每个Unix shell.
You will likely have to use some combination of batch files and/or shell scripts to accomplish what you want to do. Note that although Windows batch files can change the current directory of the shell in which they run, this is not true of shell scripts on Unix. In the case of Unix, you will probably want to use shell functions, which do run in the same process. Note that writing shell functions is shell-specific, so you'd have to port your program to each Unix shell that you want to support, too.
在某些Unix shell上,可以使用.
命令使shell脚本在当前shell的上下文中运行.如果您的外壳支持此功能,则可以使用外壳别名来运行它,这样就不必在命令前面键入.
.
On some Unix shells, you can make a shell script run in the context of the current shell using the .
command. If your shell supports that, you can use a shell alias to run it so you don't have to type .
in front of your command.
这篇关于以可移植的方式以编程方式更改外壳的cwd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!