vimtricks.wiki Concise Vim tricks, one at a time.

How do I set an environment variable inside Vim so it is available to shell commands I run?

Answer

:let $VAR = "value"

Explanation

Vim lets you read and write environment variables using the $VARIABLE syntax in Vimscript. Setting :let $VAR = "value" makes the variable available to any shell commands you run from within Vim via :!, :terminal, or system(). This is particularly useful for injecting configuration into build tools, test runners, or scripts without leaving the editor.

How it works

  • :let $VAR = "value" — sets the environment variable VAR to "value"
  • :echo $VAR — reads the current value of an environment variable
  • :unlet $VAR — removes the variable from the environment

The variable is available to child processes started from within Vim but is not exported back to the shell that launched Vim.

Example

Set log verbosity before running a Rust binary:

:let $RUST_LOG = "debug"
:!cargo run

Or configure a test environment:

:let $NODE_ENV = "test"
:!npm test

You can also read existing environment variables:

:echo $HOME
:echo $PATH

Or modify them:

:let $PATH = $PATH . ":/usr/local/custom/bin"

Tips

  • Useful for setting $TERM, $EDITOR, or tool-specific vars like $CARGO_INCREMENTAL before running :! commands
  • Combine with abbreviations: :cabbrev setrustlog let $RUST_LOG = "debug"
  • Variables set this way are visible to :terminal buffers and system() calls
  • Use :let $VAR = "" to clear a variable (sets it to an empty string rather than removing it)

Next

How do I accept a flagged word as correct for the current session without permanently adding it to my spellfile?