Cannot "cd" or change directory using bash script in WSL

It's because you have created your script in a windows machine, some \r (carriage return) has been added at the end of each line.

Remove them like this:

tr -d '\r' < test.sh > new-test.sh

Also quote the variable's value:

cd "$dir"

then run your script:

./new-test.sh

As a hint it's also better to use:

 cd ... || exit

in case of any failure.


Configure your editor so it uses Linux format for saving files (If it's capable of) or use an editor in bash like nano:

enter image description here


Another option is to using dos2unix command to convert the file to Unix type format.

Usage:

dos2unix your_file