Visual Studio Code: How to inherit Shell environment variables

Try the following, open a shell in your computer and enter:

Visual Studio Code: How to inherit Shell environment variables
Photo by Rayyu Maldives on Unsplash

Try the following, open a shell in your computer and enter:

export var1="hello"

This creates a variable, you can verify that the variable exists with echoing the variable

echo $var1

Now start Visual Studio Code and open a terminal, enter the same echo command, you can see that the variable is not set!

Why this is happening?

If you launch VS Code from a desktop shortcut, Start menu, or taskbar, it does not inherit environment variables from a terminal. Instead, it gets variables from system-wide settings. This means that depending on your system inherits everything that .bashrc , .zshrc , .profile have. If you work in a windows machine inherits everything that is defined in the “Environment variables” option of control panel.

Solutions

Depending on what you want to achieve there are many options

Not sure what environment variables i might use

if you dont know what environment variables you might need or not need on each session the best solution is to start visual studio code with code . from shell, if the code alias does not exist you can very easy enable wit from this menu option of visual studio code

I know what environment variables i need on each time i open visual studio code

Apart from .bashrc and other like configuration options, visual studio code offers a dedicated configuration file which you can set environment variables available to visual studio code terminal, this file is called “Integrated Terminal Startup Script”, to find it open visual studio code settings using ctrl , + or cmd , + if you are in a Mac and search for “terminal.integrated.env”, Then depending on What operating system you are select the appropriate option

In the following example i added a variable named MY_ENV_VAR with a value of hello

Save changes and close Visual Studio Code and starting again and open a terminal, we can see that the defined variable exists now.

note that the reverse does not work, this variable is not present in shells opened outside Visual Studio Code.

Conclusion

There are three ways to inherit environment variables

  • system wide variables from files like .bashrc , .zshrc etc.
  • typing the environment variables in a terminal and then start visual studio code with code .
  • using the settings.json configuration file.