1

I'm writing a simple bash script to create a new directory. The last line to cd into the $dir is not executing. If I change it to echo "Hello world" it works, if I change it to cd ../, it does not work. Everything else in the script is functioning as it should.

clear
read -p "Directory Name  : " name
echo "Creating a directory called " $name
cd ~/Sites
mkdir $name
cd $name

2 Answers2

2

This is (I'm assuming) the line of code you wrote in your interactive shell to execute your script:

./FooScript.sh

Which is interpreted the exact same way as writing:

bash FooScript.sh

This causes your script to be executed in a subshell. Your subshell has its own concept of where it is in your file system. So, you changed the directory of the subshell to ~/Sites/$name directory, but not the directory of the interactive shell.

There are two ways you can fix your problem - try executing your script again in either one of two ways:

source FooScript.sh

. FooScript.sh

This way, your script runs inside the same process as your interactive shell, rather than inside a subshell as a new process.

zxgear
  • 1,168
  • 14
  • 30
1

cd does work in the script but it does not affect the calling process, that is, the shell.

If you source the script with . foo, it should work.

lhf
  • 70,581
  • 9
  • 108
  • 149