Automatically List Directory Contents When Changing Directory In Linux

When navigating around a Linux box I tend to find I use the same two commands a lot. The first is 'cd' to change a directory, and the second is 'ls' in order to see what is in the new directory. Rather than do this over and over again I decided to look around for a good solution to automate this.

I found a variety of results on the internet, but some were simply creating a different alias that wrapped the same two commands. I found this example on superuser, which solves the problem quite nicely. Here is the example in full.

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

What this does is to define a function called ‘cd’ which calls the built in ‘cd’ function, passing any parameters given, before then running ls on the new directory. The builtin keyword forces the cd call inside the function to use the internal cd, rather than to recursively call the function. The double ampersand (&&) is used to execute one program after another and so the ls command is run only after the cd has not encountered any errors. The upshot of this approach is that if you try to change into a directory that doesn’t exist you won’t also be told that you can’t list the contents of the non-existent directory.

You can alter function to include parameters along with the ls call in order to change its output like this.

cd() { builtin cd "$@" && ls -la; }

To use this just drop it into your .bashrc or .bash_profile file and reload it by using the source command. Now, when you change directories you will be shown a list of the directory contents. I have also tested this in Mac OS X.


What are tha advantage on doing it this way and not using Bash aliases instead?
This way seems a little cleaner.
Philip Norton

Add new comment

The content of this field is kept private and will not be shown publicly.
6 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.