Linux tip: Alias ‘cd’ in bash shell

A while ago, I stumbled across an excellent article at O’Reilly with tips for your bash shell.

I wanted to expand on the “pushd/popd” section a little.

First, check your ~/.bashrc file for the following lines:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases

This checks that the ~/.bash_aliases file exists, and if it does, it loads it using the ‘.’ builtin. If you aren’t familiar with the source/. builtin, here is an excerpt from the documentation:

. (a period)
. filename [arguments]

Read and execute commands from the filename argument in the current shell context. If filename does not contain a slash, the PATH variable is used to find filename. When Bash is not in posix mode, the current directory is searched if filename is not found in $PATH. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the exit status of the last command executed, or zero if no commands are executed. If filename is not found, or cannot be read, the return status is non-zero. This builtin is equivalent to source.

Now, create or edit ~/.bash_aliases with the following content:

alias cd="pushd"
alias bd="popd"
alias cd..="cd .."
alias cd...="cd ../.."
alias cd....="cd ../.."
alias cd.....="cd ../../.."
alias cd......="cd ../../../.."

This aliases cd to push the result onto the directory stack (pushd). Then, we introduce a bd command to pop the last directory off the stack (popd).

If you’re like me, you get tired of typing cd ../../../.., which is still faster than typing cd /home/jim/projects/al [TAB]/src or something similar. So, the last lines alias quite a few levels of directory changes so you type cd.. followed by the number of directories you want to navigate back.

Here are some examples:

jim@schubert:~$ cd projects/newtabredirect/
~/projects/newtabredirect ~

jim@schubert:~/projects/newtabredirect$ cd ~/projects/select-actions/
~/projects/select-actions ~/projects/newtabredirect ~

jim@schubert:~/projects/select-actions$ cd ~/Documents/blogs/
~/Documents/blogs ~/projects/select-actions ~/projects/newtabredirect ~

jim@schubert:~/Documents/blogs$ bd
~/projects/select-actions ~/projects/newtabredirect ~

jim@schubert:~/projects/select-actions$ cd....
~ ~/projects/select-actions ~/projects/newtabredirect ~

jim@schubert:~$ pwd

Flattr this!