Common Exec for Bash Part I

Bash

cd does not work in bash script

The bash script is running in a new process, so you the workdir is not the same with the bash command. There are five solution for this problem as follows:

  1. Symbolic link

Put a symlink in your home to the long path you want to easily access

$ ln -s /home/alex/Documents/A/B/C ~/pathABC
then access the directory with:

$ cd ~/pathABC

  1. Alias

Put an alias in your ~/.bashrc:
alias pathABC=”cd /home/alex/Documents/A/B/C”

  1. Function

Create a function that changes the directory, the function runs in the process of your terminal and can then change its directory.

  1. Avoid running as child

Source your script instead of running it. Sourcing (done by . or source) causes the script to be executed in the same shell instead of running in its own subshell.

$ . ./pathABC

  1. cd-able vars

Set the cdable_vars option in your ~/.bashrc and create an environment variable to the directory:

shopt -s cdable_vars
export pathABC=”/home/alex/Documents/A/B/C”
Then you can use cd pathABC

I use the Alias , the codes in the

as follows:
1
2
3
4
5
6

```shell
alias gd="cd ${devdir}"
alias gw="cd ${workdir}"
alias gp="cd ${prddir}"
alias gt="cd ${devdir}/github/"

Reference

Why doesn’t “cd” work in a bash shell script?

Why doesn’t “cd” work in a shell script?