Code isn’t the only thing we should endeavor to keep DRY. Let’s see if you can detect a pattern in this very common — albeit contrived for sake of example — Bash session:

jerod@mbp:~$ cd src/erlang
jerod@mbp:~/src/erlang$ ls
[snip]
jerod@mbp:~/src/erlang$ cd ..
jerod@mbp:~/src$ ls
[snip]
jerod@mbp:~/src$ cd
jerod@mbp:~$ ls
[snip]

In my experience, the cd command is almost always followed by the ls command. Why have I been typing it in all these years? Not anymore, baby!

I already have a custom cd function which provides cd ... type directory traversals (more on that here), so I recently added two characters to it.

Before

function cd () {
  if [[ $# > 0 ]]; then
    if [ ${1:0:2} == ".." ]; then
      rest=${1:2}
      rest=${rest//./../}
      builtin cd "${1:0:2}/${rest}"
    else
      builtin cd "$1"
    fi
  else
    builtin cd
  fi
}

After

function cd () {
  if [[ $# > 0 ]]; then
    if [ ${1:0:2} == ".." ]; then
      rest=${1:2}
      rest=${rest//./../}
      builtin cd "${1:0:2}/${rest}"
    else
      builtin cd "$1"
    fi
  else
    builtin cd
  fi
  ls
}

Did you spot the change? Yup, I just added the ls at the end of every cd. Little change, huge payoff. Give it a try and after a few days you’ll be wondering why you didn’t do this years ago (I know I am).

Oh, and if you don’t want the directory traversal bit, you can get away with a much more simple function:

function cd() { builtin cd $@ && ls; }

Enjoy!