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:
- 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. - 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.
How would a person go about implementing this? is this supposed to go in my ~/.bash_profile?
Nevermind… I just read the second paragraph where you mention I can put this in my .bash_profile.
Thanks for the great article!
Levi