0

I have this script in a file called /Users/tcl/scripts/gotoroot:

echo "hello"
cd /
echo "good bye"

But when I run it I get this:

User:scripts tcl$ pwd
/Users/tcl/scripts
User:scripts tcl$ gotoroot
hello
good bye
User:scripts tcl$ pwd
/Users/tcl/scripts
User:scripts tcl$

The directory has not changed and I don't know why? It should be /, not /Users/tcl/scripts

John
  • 3,458
  • 4
  • 33
  • 54

2 Answers2

6

When you run the script, it starts a subshell in a new process. The cd changes directory inside that subshell, not inside your terminal process.

Test it out by putting this in your script:

pwd
cd /
pwd

You should see that it changes to / inside the script.

user513951
  • 12,445
  • 7
  • 65
  • 82
  • 1
    Got it, thanks. This is a duplicate of https://stackoverflow.com/questions/255414/why-doesnt-cd-work-in-a-bash-shell-script. – John Aug 10 '17 at 18:41
2

Shell scripts are run inside of sub processes. The CD is working but it's happening inside a different process than your main terminal session and has no effect on the working directory once you return to your terminal session.