linux - [Solved-5 Solutions] Why doesn't “cd” work in a bash shell script ? - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
Why doesn't “cd” work in a bash shell script ?
Linux - Solution 1:
- Shell scripts are run inside a subshell, and each subshell has its own concept of what the current directory.
- The cd succeeds, but as soon as the subshell exits, you're back in the interactive shell and nothing ever changed there.
To use an alias instead:
Linux - Solution 2:
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:
Linux - Solution 3:
- The cd in your script technically worked as it changed the directory of the shell that ran the script, but that was a separate process forked from your interactive shell.
- A Posix-compatible way to solve this problem is to define a shell procedure rather than a shell-invoked command script.
Linux - Solution 4:
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:
do
Linux - Solution 5:
To make a bash script that will cd to a select directory :
Create the script file
Then create an alias in your startup file.
- Created a startup file where you dump all my aliases and custom functions.
- Then source this file into .bashrc to have it set on each boot.
For example, create a master aliases/functions file: /scripts/mastercode.sh
End of your .bashrc file: