Time saving tip: Automatically ls when changing directories

If you spend a lot of time in the shell, you may notice a certain pattern when hopping around the filesystem. You “cd” to where you want to go, then immediately “ls” to see what is in that directory. I found myself doing this extremely often, so I decided to cut my typing time down by automatically listing as I cd.

cd () {
  builtin cd "$*"
  if [ $? -eq 0 ]; then
    ls
  fi
}

This is the function I tossed in my .bashrc to accomplish the auto-ls behaviour. It attempts to call the builtin cd function, and runs ls if the cd was successful. Since my .bashrc doesn’t get interpreted in non-interactive instances, this customized function doesn’t change the behaviour of any bash scripts I run.

There are a couple instances where I don’t want to automatically list a directory; the most common being when switching into a directory with a huge amount of files. For these cases, I wrote an alias called “cdd” which retains the normal cd behavior:

alias cdd="builtin cd"

Doing a manual “ls” may not seem like a big deal, but the time and keystrokes add up over the time. Give this function a try and see how you like it. I found the switch to be pretty painless.

Happy cd’ing!

Share and Enjoy:
  • StumbleUpon
  • Facebook
  • Twitter
  • Reddit
Time saving tip: Automatically ls when changing directories

4 thoughts on “Time saving tip: Automatically ls when changing directories

  1. Tsubashi says:

    Very useful, I like it, but it has one quirk. When you just type ‘cd’ without a directory, you only get an ‘ls’ of the current directory, instead of being taken back to your home dir as one would expect. To circumvent this quirk, I modified it slightly as follows:

    cd () {
    if [ “$*” = “” ]; then
    builtin cd ~
    else
    builtin cd “$*”
    fi
    if [ $? -eq 0 ]; then
    clear
    ls –color=always
    echo
    fi
    }

    1. Phylogenesis says:

      ynnsn: Useless use of if :p

      A good combination of both the above fixes, whilst keeping it simple is:

      cd () {
      builtin cd “${*-$HOME}” && ls
      }

Leave a Reply

Your email address will not be published.