Why I can't change directories using “cd”?

后端 未结 30 2899
眼角桃花
眼角桃花 2020-11-21 06:17

I\'m trying to write a small script to change the current directory to my project directory:

#!/bin/bash
cd /home/tree/projects/java

I save

30条回答
  •  耶瑟儿~
    2020-11-21 06:45

    Use exec bash at the end

    A bash script operates on its current environment or on that of its children, but never on its parent environment.

    However, this question often gets asked because one wants to be left at a (new) bash prompt in a certain directory after execution of a bash script from another directory.

    If this is the case, simply execute a child bash instance at the end of the script:

    #!/usr/bin/env bash
    cd /home/tree/projects/java
    exec bash
    

    Update

    At least with newer versions of bash, the exec on the last line is no longer required. Furthermore, the script could be made to work with whatever preferred shell by using the $SHELL environment variable. This then gives:

    #!/usr/bin/env bash
    cd desired/directory
    $SHELL
    

提交回复
热议问题