Combining cd and ls Into One Command

Andrew Braunstein and I were discussing how one might add a shell command to change a directory and list it using one command. I’m sure anyone who uses the shell is familiar with cd followed immediately by ls.

A search found this discussion on the Unix.com forums. The suggestion was to add the following shell function to the .bashrc or .bash_profile:

cl()
{
if [ -d "$1" ]; then
cd "$1"
ls
fi
}

This works reasonably well, but I had a couple of complaints:

  1. Because the function does nothing if the argument is not a directory, when we try to cl aDirectoryThatDoesNotExist, there is no indication of the error. The shell just prints a new prompt.
  2. Also due to the check that the argument is a directory, we cannot use the default functionality of cd with no argument that returns us to the home directory.

My proposed solution is this:

cl()
{
cd $1 && ls
}

Here we take advantage of the exit code produced by the cd command to ensure that the directory change was successful before we ls. If cd exits with an error, the boolean “and” is already false, and the ls is not executed. All we see is the error message, and we remain in the same directory. This behavior seems ideal. Additionally, calling cl with no arguments changes to, and lists the home directory as expected.

cl in action

cl in action

Advertisements

About Zachary Wasserman

Currently working on www.tenayaconsulting.com
This entry was posted in Shell Scripting and tagged , , . Bookmark the permalink.

2 Responses to Combining cd and ls Into One Command

  1. Levi says:

    How would a person go about implementing this? is this supposed to go in my ~/.bash_profile?

  2. levio says:

    Nevermind… I just read the second paragraph where you mention I can put this in my .bash_profile.

    Thanks for the great article!
    Levi

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s