Automatically List Directory Contents When Changing Directory In Linux

28th January 2014

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 "[email protected]" && 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 "[email protected]" && 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.

Comments

Permalink
What are tha advantage on doing it this way and not using Bash aliases instead?

Marcelo de Fre… (Mon, 02/17/2014 - 14:48)

Permalink
This way seems a little cleaner.

philipnorton42 (Mon, 02/17/2014 - 16:05)

Add new comment

The content of this field is kept private and will not be shown publicly.