Run a Function Every Time You Change Directories with Zsh

05-20-2020

If you have a set of tasks you do every time you change directories, e.g. changing to a new project, here is a quick way to automate those tasks.

The key component is the chpwd_functions=() function. This function, short for change present working directory, runs every time the directory changes. For example, you want to make sure you have the latest code from the remote repository before starting new development. By defining a function to perform that check you can then let chpwd_functions handle checking each time you change into that new project, without having to remember.

To start we need to define our function(s) that we want to run each time we change directories.

In my ~/.zshrc file:

1
open ~/.zshrc
1
2
3
4
5
6
function check_for_latest_code {
# Check if this directory is a .git repository
# Change branches, check for latest code, etc
# list files
# ...
}

Then we pass the new function(s) into our chpwd_functions definition:

1
chpwd_functions=(check_for_latest_code)

And re-source the ~/.zshrc file:

1
source ~/.zshrc

Now, each time we change directories our function(s) will be called. It’s important to remember to check if the new pwd has the information you need before executing your function.