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 )
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.
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?
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.
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.
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.
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.
Manipulating the working directory of a shell is something that must be done by the shell itself - you cannot write a program to do it. As for your second question, please post an example of what you are asking about.
The solution would be to make a shell function which runs the program and then does a cd on the result.
mycd()
{
cd `mycdprogram "$@"`
}
You can run it like mycd Please change my directory to /tmp
or whatever arguments your program takes.
For the other command, you can do something like:
myrun()
{
eval `myprogram "$@"`
}
And the shell will do whatever shell command myprogram generates.
All of this for POSIX shells of course.
$(echo "cd /foo/bar")
That demonstrates how you might do such a thing with a POSIX shell. It's not portable with the Windows shell, of course.