Programmatically change the shell's cwd in a portable way

前端 未结 4 1756
旧时难觅i
旧时难觅i 2021-01-21 04:44

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 cur

4条回答
  •  囚心锁ツ
    2021-01-21 05:12

    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.

提交回复
热议问题