Direnv
Many people use direnv to load an environment when entering a directory and unload it when exiting the directory.
How direnv works
From direnv.net:
Before each prompt, direnv checks for the existence of a
.envrcfile (and optionally a.envfile) in the current and parent directories. If the file exists (and is authorized), it is loaded into a bash sub-shell and all exported variables are then captured by direnv and then made available to the current shell.
Configuring direnv in Nushell
In Nushell, it's possible to run direnv each time the prompt displays (using a pre_prompt hook). However, it's more efficient to update only when the directory is changed using an env_change hook along with:
from jsonto convert the direnv output to structured dataload-env, which also turns thePATHstring that direnv exports into a list
Note
The direnv configuration below requires Nushell 0.117 or later.
# Initialize the PWD hook as an empty list if it doesn't exist
$env.config.hooks.env_change.PWD = $env.config.hooks.env_change.PWD? | default []
$env.config.hooks.env_change.PWD ++= [{||
if (which direnv | is-empty) {
# If direnv isn't installed, do nothing
return
}
direnv export json | from json | default {} | load-env
}]As with other configuration changes, this can be made permanent by adding it to your startup configuration.
With this in place, direnv will now add/remove environment variables when entering/leaving a directory with an .envrc or .env file.