Programmatically change the shell's cwd in a portable way

前端 未结 4 1761
旧时难觅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:05

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-21 05:12
    $(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.

    0 讨论(0)
  • 2021-01-21 05:15

    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.

    0 讨论(0)
提交回复
热议问题