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

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

    As explained on the other answers, you have changed the directory, but only within the sub-shell that runs the script. this does not impact the parent shell.

    One solution is to use bash functions instead of a bash script (sh); by placing your bash script code into a function. That makes the function available as a command and then, this will be executed without a child process and thus any cd command will impact the caller shell.

    Bash functions :

    One feature of the bash profile is to store custom functions that can be run in the terminal or in bash scripts the same way you run application/commands this also could be used as a shortcut for long commands.

    To make your function efficient system widely you will need to copy your function at the end of several files

    /home/user/.bashrc
    /home/user/.bash_profile
    /root/.bashrc
    /root/.bash_profile
    

    You can sudo kwrite /home/user/.bashrc /home/user/.bash_profile /root/.bashrc /root/.bash_profile to edit/create those files quickly

    Howto :

    Copy your bash script code inside a new function at the end of your bash's profile file and restart your terminal, you can then run cdd or whatever the function you wrote.

    Script Example

    Making shortcut to cd .. with cdd

    cdd() {
      cd ..
    }
    

    ls shortcut

    ll() {
      ls -l -h
    }
    

    ls shortcut

    lll() {
      ls -l -h -a
    }
    

提交回复
热议问题