Bash – Use alias and carry it on

aliasbashrc

Let's say I have this alias in my .bashrc

alias somedir="cd /var/www/site"

how can I use somedir in say … a cd command?

e.g.

cd somedir/app/

doing this currently returns:

-bash: cd: somedir/app: No such file or directory

Is it even possible to use an alias this way?

Best Answer

The bash shell has a CDPATH shell variable that helps you do this without an alias:

 $ CDPATH=".:/var/www/site"
 $ cd app
 /var/www/site/app

If there's a subdirectory of app called doc:

 $ cd app/doc
 /var/www/site/app/doc

With a CDPATH value of .:/var/www/site, the cd command will first look in the current directory for the directory path given on the command line, and if none is found it will look under /var/www/site.

From the bash manual:

CDPATH

The search path for the cd command. This is a colon-separated list of directories in which the shell looks for destination directories specified by the cd command. A sample value is ".:~:/usr".

Note that CDPATH should not be exported as you usually do not want this variable to affect bash scripts that you run from your interactive session.

Related Question