Search code examples
bashshellcd

Not able to change directory from bash script despite sourcing


I have following 2 files:

file cd2vcaa (in path):

#! /bin/bash
cd /var/cache/apt/archives

file test.sh (in current directory):

#! /bin/bash
. cd2vcaa

From terminal, I am able to change directory with . cd2vcaa but not with ./test.sh

~$ cd2vcaa                        <-- no effect
~$ . cd2vcaa                      <-- changes directory
/var/cache/apt/archives$ cd       <-- back to home directory
~$ ./test.sh                      <-- does not change directory though no error - why?
~$

Why is . cd2vcaa working from terminal but from within another script? How can this problem be solved?


Solution

  • The test.sh runs in a separate shell when you invoke it using ./test.sh, so although the sourcing inside test.sh means that the cd command will affect the current directory in the shell in which test.sh runs, so for example any commands added at the end of test.sh would run with current directory /var/cache/apt/archives, it will not affect the parent shell (your login session).

    If you invoke the test.sh by sourcing it (. test.sh), then no sub-shell is launched at either stage, and the directory is changed in your login session.

    As discussed in the comments, if the aim is simply to have use of an interactive shell which is cd-ed to the specified directory (not necessarily the parent shell), then one option is just to put bash at the end of the test.sh in order to start an interactive subshell after the cd command has been run. On exit from this subshell, control will return to the login shell, still in its original working directory.