- HowTo: Set an Environment Variable in Windows — Command Line and Registry
- Print environment variables
- Command Prompt
- Command Prompt — C:\>
- Output
- Command Prompt — C:\>
- Output
- Windows PowerShell
- Windows PowerShell — PS C:\>
- Output
- Windows PowerShell — PS C:\>
- Output
- Set Environment Variables
- User Variables
- Command Prompt — C:\>
- Command Prompt — C:\>
- Output
- System Variables
- Command Prompt — C:\>
- Registry
- Printing Environment Variables
- Environment. Set Environment Variable Метод
- Определение
- Перегрузки
- SetEnvironmentVariable(String, String)
- Параметры
- Исключения
- Примеры
- Комментарии
- How To Set Environment Variables
- Environment Variables.
- Windows Environment Variables
- macOS and Linux Distributions
- Cloud Providers
- Summary
HowTo: Set an Environment Variable in Windows — Command Line and Registry
Environment variables are not often seen directly when using Windows. However there are cases, especially when using the command line, that setting and updating environment variables is a necessity. In this series we talk about the various approaches we can take to set them. In this article we look at how to interface with environment variables using the Command Prompt and Windows PowerShell. We also note where in the registry the environment variables are set, if you needed to access them in such a fashion.
Print environment variables
You can use environment variables in the values of other environment variables. It is then helpful to be able to see what environment variables are set already. This is how you do it:
Command Prompt
List all environment variables
Command Prompt — C:\>
Output
Print a particular environment variable:
Command Prompt — C:\>
Output
Windows PowerShell
List all environment variables
Windows PowerShell — PS C:\>
Output
Print a particular environment variable:
Windows PowerShell — PS C:\>
Output
Set Environment Variables
To set persistent environment variables at the command line, we will use setx.exe . It became part of Windows as of Vista/Windows Server 2008. Prior to that, it was part of the Windows Resource Kit. If you need the Windows Resource Kit, see Resources at the bottom of the page.
setx.exe does not set the environment variable in the current command prompt, but it will be available in subsequent command prompts.
User Variables
Command Prompt — C:\>
Open a new command prompt.
Command Prompt — C:\>
Output
System Variables
To edit the system variables, you’ll need an administrative command prompt. See HowTo: Open an Administrator Command Prompt in Windows to see how.
Command Prompt — C:\>
Registry
The location of the user variables in the registry is: HKEY_CURRENT_USER\ Environment . The location of the system variables in the registry is: HKEY_LOCAL_MACHINE\ SYSTEM\ CurrentControlSet\ Control\ Session Manager\ Environment .
When setting environment variables through the registry, they will not recognized immediately. One option is to log out and back in again. However, we can avoid logging out if we send a WM_SETTINGCHANGE message, which is just another line when doing this programatically, however if doing this on the command line it is not as straightforward.
One way is to get this message issued is to open the environment variables in the GUI, like we do in HowTo: Set an Environment Variable in Windows — GUI; we do not need to change anything, just open the Environment Variables window where we can see the environment variables, then hit OK .
Another way to get the message issued is to use setx , this allows everything to be done on the command line, however requires setting at least one environment variable with setx .
Printing Environment Variables
With Windows XP, the reg tool allows for accessing the registry from the command line. We can use this to look at the environment variables. This will work the same way in the command prompt or in powershell. This technique will also show the unexpanded environment variables, unlike the approaches shown for the command prompt and for powershell.
Environment. Set Environment Variable Метод
Определение
Создает, изменяет или удаляет переменную среды. Creates, modifies, or deletes an environment variable.
Перегрузки
Создает, изменяет или удаляет переменную среды, хранящуюся в текущем процессе. Creates, modifies, or deletes an environment variable stored in the current process.
Создает, изменяет или удаляет переменную среды, хранящуюся в текущем процессе или разделе реестра операционной системы Windows, зарезервированном для текущего пользователя или локального компьютера. Creates, modifies, or deletes an environment variable stored in the current process or in the Windows operating system registry key reserved for the current user or local machine.
SetEnvironmentVariable(String, String)
Создает, изменяет или удаляет переменную среды, хранящуюся в текущем процессе. Creates, modifies, or deletes an environment variable stored in the current process.
Параметры
Имя переменной среды. The name of an environment variable.
Значение, которое необходимо присвоить параметру variable . A value to assign to variable .
Исключения
variable имеет значение null . variable is null .
variable содержит строку нулевой длины, начальный шестнадцатеричный символ нуля (0x00) или знак равенства («=»). variable contains a zero-length string, an initial hexadecimal zero character (0x00), or an equal sign («=»).
Длина параметра variable или value больше или равна 32 767 символам. The length of variable or value is greater than or equal to 32,767 characters.
Во время выполнения этой операции произошла ошибка. An error occurred during the execution of this operation.
У вызывающего объекта отсутствует необходимое разрешение для выполнения этой операции. The caller does not have the required permission to perform this operation.
Примеры
В следующем примере предпринимается попытка получить значение переменной среды с именем Test1 из блока Process окружения. The following example attempts to retrieve the value of an environment variable named Test1 from the process environment block. Если переменная не существует, в примере создается переменная и извлекается ее значение. If the variable doesn’t exist, the example creates the variable and retrieves its value. В примере отображается значение переменной. The example displays the value of the variable. Для реализаций .NET, выполняемых в системах Windows, он также вызывает GetEnvironmentVariables(EnvironmentVariableTarget) метод с каждым членом EnvironmentVariableTarget перечисления, чтобы определить, что переменную можно извлечь только из текущего блока среды процесса. For .NET implementations running on Windows systems, it also calls the GetEnvironmentVariables(EnvironmentVariableTarget) method with each member of the EnvironmentVariableTarget enumeration to establish that the variable can be retrieved only from the current process environment block. (Реализации .NET в системах на базе UNIX поддерживают только переменные в блоке среды Process.) Наконец, если в примере создается переменная, она удаляет ее. (.NET implementations on Unix-based systems only support variables in the process environment block.) Finally, if the example created the variable, it deletes it.
Комментарии
Вызов этого метода эквивалентен вызову SetEnvironmentVariable(String, String, EnvironmentVariableTarget) перегрузки со значением EnvironmentVariableTarget.Process для target аргумента. Calling this method is equivalent to calling the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) overload with a value of EnvironmentVariableTarget.Process for the target argument.
Если value аргумент не пуст (см. Обсуждение удаления переменной среды далее в этом разделе для определения пустого значения), а переменная среды с именем в variable параметре не существует, переменная среды создается и присваивается содержимое value . If the value argument is not empty (see the discussion of deleting an environment variable later in this section for the definition of an empty value) and the environment variable named by the variable parameter does not exist, the environment variable is created and assigned the contents of value . Если он существует, его значение изменяется. If it does exist, its value is modified. Так как переменная среды определена в блоке среды только текущего процесса, она не сохраняется после завершения процесса. Because the environment variable is defined in the environment block of the current process only, it does not persist after the process has ended.
Если variable содержит неначальный шестнадцатеричный нуль-символ, символы перед нулевым символом считаются именем переменной среды, а все последующие символы игнорируются. If variable contains a non-initial hexadecimal zero character, the characters before the zero character are considered the environment variable name and all subsequent characters are ignored.
Если value содержит неначальный шестнадцатеричный нуль-символ, то символы перед нулевым символом присваиваются переменной среды, а все последующие символы игнорируются. If value contains a non-initial hexadecimal zero character, the characters before the zero character are assigned to the environment variable and all subsequent characters are ignored.
Если value параметр пуст и переменная среды с именем variable существует, переменная среды удаляется. If value is empty and the environment variable named by variable exists, the environment variable is deleted. Если не variable существует, ошибка не возникает, даже если операция не может быть выполнена. If variable does not exist, no error occurs even though the operation cannot be performed. value считается пустым при выполнении любого из следующих условий: value is considered empty under any of the following conditions:
Это null . It is null .
Он состоит из одного символа, значение которого равно U + 0000. It consists of a single character whose value is U+0000.
How To Set Environment Variables
There are some things we just shouldn’t share with our code. These are often configuration values that depend on the environment such as debugging flags or access tokens for APIs like Twilio. Environment variables are a good solution and they are easy to consume in most languages.
Environment Variables.
Environment variables, as the name suggests, are variables in your system that describe your environment. The most well known environment variable is probably PATH which contains the paths to all folders that might contain executables. With PATH , you can write just the name of an executable rather than the full path to it in your terminal since the shell will check the local directory as well as all directories specified in the PATH variable for this executable.
Aside from ‘built-in’ variables we also have the opportunity to define our own environment variables. Since they are bound to our environment they are great for things such as API access tokens. You could have a variable set to one value on your development machine and another in your production environment without having if -statements or special config files.
Twilio’s helper libraries for example, look for the TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables if you instantiate a client without the two values. This way you don’t have to worry about accidentally pushing sensitive credentials to a place such as GitHub.
Windows Environment Variables
Setting environment variables in Windows is pretty hidden in several layers of settings dialogs. Just like most things in Windows, we will set environment variables using a graphical user interface. To open the respective interface you first have to open the Windows Run prompt. Do so by pressing the Windows and R key on your keyboard at the same time. Type sysdm.cpl into the input field and hit Enter or press Ok.
In the new window that opens, click on the Advanced tab and afterwards on the Environment Variables button in the bottom right of the window.
The window has two different sections. One is the list of environment variables that are specific to your user. This means they aren’t available to the other users. The other section contains the system-wide variables that are shared across all users.
Create a user specific variable by clicking the New button below the user-specific section. In the prompt you can now specify the name of your variable as well the value. Create a new variable with the name TWILIO_ACCOUNT_SID and copy your Twilio Account SID from the Console. Press Ok in the prompt to create the variable, followed by Ok on the Environment Variables window. You are all set now.
To test if it worked open the Command Prompt by pressing Windows R and typing cmd.exe . If you have the Command Prompt open already, make sure to restart it to ensure your changes are applied. Inside the Command Prompt execute the following command:
This should print the value that you saved in the environment variable.
macOS and Linux Distributions
In order to set environment variables on macOS or any UNIX based operating system you first have to figure out which shell you are running. You can do that by running in your terminal the command:
The end of the output should indicate which shell you are running. The typical shell is the bash shell which we will be using in this example. But the steps are similar for other shells like zsh or fish .
In order to set an environment variable we need to use the export command in the following format:
Since this would only set this for our current session we need to add this command into a file that is executed for every session. For this open the .bashrc file in your home directory with your favorite code editor. Add the following line somewhere in your .bashrc file:
Replace youraccountsid with your actual Account SID from your Twilio Console. Save the file and open a new terminal instance to test if it worked by running:
You should see the value that you stored in it.
In some situations you only need an environment variable set for only a single project. In that case .env files are a great solution. It’s a file inside your project in which you specify these environment variables and afterwards you use a library for your respective programming language to load the file which will dynamically define these variables.
There are libraries for most programming languages to load these files. Here are a few:
Create a .env file in your project folder (typically at the root) and place the key value pairs in there. This can look like this:
Now all you need to do is consume the respective library and then you can use the environment variable. In Node.js the respective code would look like this:
Since you most likely don’t want to commit your environment variables to a repository, make sure to add the .env file to your .gitignore to avoid accidentally pushing it.
Cloud Providers
Setting environment variables on your local development machine or in a VM is only half the work. What if we are hosting our application in a cloud environment such as Heroku, Azure or AWS or even wrap it in a Docker container? Luckily, all of these providers support ways to define environment variables. You can find instructions on how to set them in their documentations:
If you can’t find your cloud host among this list it doesn’t necessarily mean there is no way to configure environment variables. Make sure to check their documentation for more on it.
Summary
That’s it! Now you can set environment variables which means that you can take all of your environment based configuration values out of your code and make your code more flexible and safe!
Be mindful that these values are still stored in plain text. If you are planning to store very sensitive values you should look into something like a secret storage solution such as Vault.