---
title: Run a Function Every Time You Change Directories with Zsh
description: 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.
date: 2020-05-20
tags: Zsh
source: https://brianchildress.co/blog/run-function-when-changing-directories
---

# Run a Function Every Time You Change Directories with Zsh

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 _**ch**ange **p**resent **w**orking **d**irectory_, 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:

```sh
open ~/.zshrc
```

```sh
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:

```sh
chpwd_functions=(check_for_latest_code)
```

And re-source the _~/.zshrc_ file:

```sh
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.
