bookmark_borderWhy doesn’t CD work in a Shell Script? How can I make CD work in a Shell Script?

If you have ever tried to run the current directory (CD) command inside your shell script you’ll notice it doesn’t work.

Example

#!/bin/bash
cd /home/$user/Documents/test-directory

This is because shell scripts run inside a subshell, and each subshell has its own concept of what the “current directory” is. In fact, it’s not that the cd doesn’t execute, it actually does but the minute it exits the subshell you’re back in the original shell and nothing changed.

Continue reading “Why doesn’t CD work in a Shell Script? How can I make CD work in a Shell Script?”