“cd” My Way In Linux Using Bash Function

The “cd” binary that comes with most Linux based distros is good and all but this being Linux, I thought I would enhance its features a bit. I decided to create a simple bash function called “cd” which is sourced at startup by my .bashrc file so that every time I run the Linux command “cd”, the present working directory, or “pwd” is printed as well.

“Why would I want such a dumb feature since I should already know where I am going if I am using the “cd” command”, you ask? Glad you asked so I will tell you young grasshoppa’. Currently on my system, when you change directories using the “cd” command, the present working directory is not printed to give you a nice hand holding feeling. So, for example, when you run commands like “cd ..”, “cd -“, or “cd ../../../”, you are kinda left to guess where you might be. In comes my “cd” function.

NOTE: Its important the the function be named “cd” so if you intend to use it, copy and paste everything below to your $HOME/.bashrc file and source it. How to do that is beyond the scope of this article.

# $PWD is printed when $USER changes dirs
# just the way I like it -> jtnez
cd ()
     if [ "$1" = "-" ]; then
        builtin cd $1;
     elif [ $# = 0 ]; then 
          builtin cd $HOME
          echo $PWD
         builtin cd $1;
         echo $PWD

Thats it. Now every time you use the “cd” command, you will be shown the present working directory. If for some reason you want to use “cd” in a script and don’t want anything printed to screen, in your scripts, use:

\\cd /path/to/directory/here/

In bash, starting a command with a “\” (backwards slash) will remove any previous alias and use the systems binary without any of the whiz bang options we added above. Its a small tip but hey, try it out!

Ok, but how do I install it? No installation necessary, just append the contents of the above code to your $HOME/.bashrc file, log out of your shell then re-login. Thats it!

About this entry