How to run a command after changing directories in zsh

About once a year or so, I go through my dotfiles and do some clean
up. Usually around spring time, but also, usually after I discover some new
hotness that I had not known about that I want to leverage.

This year, it’s both. Spring is nearly in the air, and I’ve been wanting to port
my stuff to use GNU stow as well as take advantage of zsh hooks.

My interest in zsh hooks is because of a little trick that I implemented years
ago, to automatically display the contents of a directory with ls after
changing into the directory, using cd.

The route I took initially, which does work in both bash and zsh and
probably other shells, is to create a function that replaces cd that runs both
cd and ls as such:

# `ls` after `cd`
function cd {
	builtin cd "$@" && ls
}

My recent discovery of zsh hooks got me excited enough to rethink my previous
solution. The hooks work more like a side effect instead of munging with the
original command.

The same solution using the zsh hook that gets executed after the you change a
directory looks like this:

autoload -U add-zsh-hook

ls_after_cd() {
	ls
}

add-zsh-hook chpwd ls_after_cd

Definitely a bit wordier, but I’d argue that this is “the Z shell way” to go
about this. Obviously, this wouldn’t work in other shells and is zsh specific.

In all honesty, I wasn’t very happy with the syntax and also came to realize
that neither my original solution nor the zsh hook solution allowed me the
option to run cd without running ls.

This got me to ask myself “self, why did you opt to write a function instead of
creating a new alias?”

Well I went ahead and tried that, and turns out, it didn’t quite work the way I
expected it to.

Interestingly enough, it would seemingly change to the directory, would list the
contents of the destination directory, but then I would still be in the same
directory that I had started with.

Figuring out how to create an alias for this would have been nice, but I didn’t
want to spend all day trying to figure it out, as I still had more spring
cleaning to do for my dotfiles!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.