`cd` not working if used in bash script [duplicate]

I cannot use cd anymore when using it in a bash script

[~/Downloads] # cat cd-backward
#!/bin/bash
cd ..

[~/Downloads] # ./cd-backward
[~/Downloads] #

I should move to ~ at the last line.

cd works perfectly in terminal strangely. Nothing happens also when I run bash -c 'cd Download for instance.


Every script is executed in its own subshell, that is a separate process that cannot modify its parent working directory. The only way to change a working directory using a script written to a file is sourcing it using . or source (they are equivalent) like this:

$ . cd-backward

or

$ source cd-backward

Note that in such case you don't even need shebang (#!/bin/bash) at the top of your script.


When you launch a script, it runs in its own shell, as Arkadiusz already mentioned. In this case, you have instance of bash. You can see it if you modify the script:

#!/bin/bash
cd ..
pwd

Sample run on my system gives :

bash-4.3$ pwd
/home/xieerqi/Downloads
bash-4.3$ ./cd-backward 
/home/xieerqi
bash-4.3$ pwd
/home/xieerqi/Downloads

Appropriately enough, within the script subshell, you navigate to home directory. Parent shell's current working directory however remains unchanged