cd && ls

I’ve noticed that I have a habit of changing to a directory and then immediately listing it’s contents. Wouldn’t it be nice if I could do it in one command?

My goto for shell automation is usually shell scripting. Shell scripting is nice because I can use any language I want, and I don’t have to worry about losing everything if I switch shells or something. Shell scripting isn’t suitable for this, however, because writing cd in a shell script will just change the script’s working directory.

I notice that a lot of people like to use aliases for various little things like command abbreviations, but aliases can’t interpolate arguments. Without control over arguments, I can’t give cd the argument and then ls after that.

The final solution I wrote is a bash function in my .bashrc, and while it’s bash-specific, I doubt I’ll ever need to port it to another shell (and it shouldn’t be difficult to do either).

cl () { cd \$1 && ls; }

Now I just need to train my fingers to type “cl” instead.

One Response to “cd && ls”

  1. sean writes:

    Very nice Eric! I was going down a long and complicated road, then decided to re-google and saw this. Elegant.

    So if your fingers are die-hard `cd` fans, you can always open up `.bash_profile` and alias your `cd` command to invoke `cl`

    alias cd=”cl”

    Cheers!

Leave a Reply