0

I am new to bash scripting. This might be obvious to many. please bear with me.

I have a shell script as follows:

#!/bin/bash
echo `pwd`
cd /home/foo/bar
echo `pwd`

Let's say I am currently in dir : /home/foo1

If I execute the above script it prints:

/home/foo1
/home/foo/bar

But once the script completes execution, I have seen that it still remains in dir /home/foo1

I have also seen some scripts where there are explicit commands to reset the working dir using 'cd -' command.

If bash executes all the lines in the script as commands, why does it again reset the working dir?

iwekesi
  • 2,228
  • 4
  • 19
  • 29

1 Answers1

1

When you are running an interactive session of bash, and from it, you execute a script (e.g. ./myscript.sh), then bash creates a new bash process to execute the script. Initially, that process get copy of the same environment as the original process (e.g. the current working directory, or environment variables), but if the script modifies the environment somehow, this changes only affect the new process, not the original one. So when the scripts exits, you go back to the original process which retains the original environment. So it is not possible to modify the current directory of the original shell from a script.

As a side note, the following line

echo `pwd`

does not make much sense. You either have to do echo $PWD or simply pwd.

redneb
  • 21,794
  • 6
  • 42
  • 54