Nushell
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
  • 한국어
GitHub
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
  • 한국어
GitHub
  • Cookbook

    • Cookbook
    • Setup
    • Help
    • System
    • Parsing
    • Foreign Shell Scripts
    • Pattern Matching
    • Custom Completers
    • External Completers
    • Module Scenarios
    • Files
    • Git
    • Parsing Git Log
    • Acting on keypresses using `input listen`
    • HTTP
    • Direnv
    • ssh-agent
    • Advanced table workflows
    • Polars vs Pandas vs Nushell
    • jq vs Nushell

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 .envrc file (and optionally a .env file) 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 json to convert the direnv output to structured data
  • load-env
  • An env-conversion helper for the PATH from the Standard Library

Note

The direnv configuration below requires Nushell 0.104 or later.

use std/config *

# 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
  # If direnv changes the PATH, it will become a string and we need to re-convert it to a list
  $env.PATH = do (env-conversions).path.from_string $env.PATH
}]

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.

Edit this page on GitHub
Contributors: John Axel Eriksson, Samir Talwar, amtoine, Liam Griffin-Jowett, fdncred, Joaquín Triñanes, Justin Ma, Fawad Halim, Jasha10, NotTheDr01ds
Prev
HTTP
Next
ssh-agent