Ubuntu – `cd` not working if used in bash script


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

[~/Downloads] # cat cd-backward
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.

Best Answer

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


$ source cd-backward

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