Unmangling paths set by direnv on Windows 11

direnv works fine on Windows 11, but if an .envrc tries to set the PATH, the result will be a path in Windows format, not Unix format.1

Instead of adding eval $(direnv hook bash) to your .bashrc, try the following snippet:

export _unmangle_direnv_names='PATH'
_unmangle_direnv_paths() {
    for k in $_unmangle_direnv_names; do
        eval "$k=\"\$(/usr/bin/cygpath -p \"\$$k\")\""
eval "$(direnv hook bash | sed -e 's@export bash)@export bash)\

This modifies the output of direnv hook bash slightly, adding code to fix path-like variables after direnv sets the environment up.2

The variable names to unmangle are drawn from a new variable, _unmangle_direnv_names, initially set to PATH, which should contain a space-separated list of variable names.

If, in a particular .envrc, you need path-unmangling for an additional variable, you can add that variable’s name to _unmangle_direnv_names. For example,

_unmangle_direnv_names="$_unmangle_direnv_names XPATH"
export PATH="$PATH:some_addition"
export XPATH="$PATH:some_addition"

will unmangle both PATH and XPATH.

  1. See direnv issues 253 (“PATH gets mangled when using direnv from git-bash on Windows”) and 796 (“Incorrect path format is exported on Windows 10 with mintty / git bash, breaking the PATH and command resolution”). 

  2. While experimenting, I discovered direnv export json! Very nice. It’s great to see more and more tools using structured data for their inputs and outputs.