0

Here is my script to change the directory

[user@linux ~]$ cat script.sh
echo Before: $(pwd)
cd "$1"
echo After : $(pwd)
[user@linux ~]$

When I tested it, it did not really change the directory as shown in the last pwd command.

Manual pwd command

[user@linux ~]$ pwd
/home/user
[user@linux ~]$

Test 1

[user@linux ~]$ script.sh dir01/
Before: /home/user
After : /home/user/dir01
[user@linux ~]$

Test 2

[user@linux ~]$ script.sh /home/user/dir01
Before: /home/user
After : /home/user/dir01
[user@linux ~]$

Manual pwd command again after that

[user@linux ~]$ pwd
/home/user
[user@linux ~]$

What's wrong with my code?

1 Answers1

2

Your script is launched in a new non-interactive shell that is forked from your current shell (interactive). Any changes made on the new spawned shell are reflected only for the lifetime of the script. So in your case, the cd to the new path is reflected only in the new shell and will be not be reflected back to the parent shell because the spawned shell exits when your script terminates.

You can run your script in the same shell as the one you are launching the script from using the built-in source command (in bash) or POSIX-ly using . command when the script is made executable. Try doing

. script.sh

or in bourne again shell bash, using source

source script.sh
Inian
  • 12,807