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 variableVARto"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_INCREMENTALbefore running:!commands - Combine with abbreviations:
:cabbrev setrustlog let $RUST_LOG = "debug" - Variables set this way are visible to
:terminalbuffers andsystem()calls - Use
:let $VAR = ""to clear a variable (sets it to an empty string rather than removing it)