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:

alias proj="cd /home/tree/projects/java"
click below button to copy the code. By - Linux tutorial - team

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:

. proj
click below button to copy the code. By - Linux tutorial - team

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.
jhome () {
  cd /home/tree/projects/java
}
click below button to copy the code. By - Linux tutorial - team

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:

./myscript.sh
click below button to copy the code. By - Linux tutorial - team

do

. ./myscript.sh
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 5:

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
click below button to copy the code. By - Linux tutorial - team

Then create an alias in your startup file.

#!/bin/sh
# file /scripts/mastercode.sh
#
alias cdjava='. /scripts/cdjava'
click below button to copy the code. By - Linux tutorial - team
  • 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:

source /scripts/mastercode.sh
click below button to copy the code. By - Linux tutorial - team

Related Searches to - linux - linux tutorial - Why doesn't “cd” work in a bash shell script