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

后端 未结 30 2112
眼角桃花
眼角桃花 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:26

    It is an old question, but I am really surprised I don't see this trick here

    Instead of using cd you can use

    export PWD=the/path/you/want
    

    No need to create subshells or use aliases.

    Note that it is your responsibility to make sure the/path/you/want exists.

    0 讨论(0)
  • 2020-11-21 06:27

    You're doing nothing wrong! You've changed the directory, but only within the subshell that runs the script.

    You can run the script in your current process with the "dot" command:

    . proj
    

    But I'd prefer Greg's suggestion to use an alias in this simple case.

    0 讨论(0)
  • 2020-11-21 06:27

    To make a bash script that will cd to a select directory :

    Create the script file

    #!/bin/sh
    # file : /scripts/cdjava
    #
    cd /home/askgelal/projects/java
    

    Then create an alias in your startup file.

    #!/bin/sh
    # file /scripts/mastercode.sh
    #
    alias cdjava='. /scripts/cdjava'
    

    • I created a startup file where I dump all my aliases and custom functions.
    • Then I source this file into my .bashrc to have it set on each boot.

    For example, create a master aliases/functions file: /scripts/mastercode.sh
    (Put the alias in this file.)

    Then at the end of your .bashrc file:

    source /scripts/mastercode.sh
    



    Now its easy to cd to your java directory, just type cdjava and you are there.

    0 讨论(0)
  • 2020-11-21 06:27

    to navigate directories quicky, there's $CDPATH, cdargs, and ways to generate aliases automatically

    http://jackndempsey.blogspot.com/2008/07/cdargs.html

    http://muness.blogspot.com/2008/06/lazy-bash-cd-aliaes.html

    https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5827311.html

    0 讨论(0)
  • 2020-11-21 06:28

    The cd is done within the script's shell. When the script ends, that shell exits, and then you are left in the directory you were. "Source" the script, don't run it. Instead of:

    ./myscript.sh
    

    do

    . ./myscript.sh
    

    (Notice the dot and space before the script name.)

    0 讨论(0)
  • 2020-11-21 06:29

    When you fire a shell script, it runs a new instance of that shell (/bin/bash). Thus, your script just fires up a shell, changes the directory and exits. Put another way, cd (and other such commands) within a shell script do not affect nor have access to the shell from which they were launched.

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