Changing the directory in scripts

The cd builtin works both interactively or as part of a script; in fact, you can change the directory inside of a script run from Bash, and it will not change your running shell. Suppose we had a script in the lstemp.bash file with the following two commands:

cd /tmp
ls

We can run that script from any directory, and even though part of the script is to change the directory to /tmp, we won't be left there:

$ pwd
/home/bashuser/scripts
$ ls
lstemp.bash
$ bash lstemp.bash
tmpfile1 tmpfile2 tmpfile3
$ pwd
/home/bashuser/scripts

This is because the script runs as its own subprocess, and hence has its own working directory that can be changed without affecting any other process. We'll learn more about this in the ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.