Переменные окружения (среды) в Windows содержат различную информацию о настройках системы и среды пользователя. Различают переменные окружения пользователя, системы и процессов.
Самый простой способ просмотреть содержимое переменных окружения в Windows – открыть свойства системы (sysdm.cpl) -> Дополнительно -> Переменные среды. Как вы видите, в открывшемся есть две секции: в верхней содержатся переменные окружения пользователя, в нижнем – системные.
Кроме того, переменные среды хранятся в реестре системы. Пользовательские переменные хранятся в разделе HKEY_CURRENT_USER\Environment. Системные – в HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.
Вывести значения всех переменных окружения можно в командной строке Windows. Команда простая:
Set
Команда выведет список переменных среды и их значения.
В PowerShell для вывод всех переменных окружения можно использовать команду:
ls env:
Если нужно вывести значение только одной переменной, нужно воспользоваться командой echo, причем имя переменной нужно заключить в знаки процентов. Например,
Echo %systemroot%
Чтобы сохранить все переменные среды и их значения в текстовый файл, воспользуйтесь командой:
set > c:\tmp\env_var.txt
Переменные окружения конкретного процесса можно получить с помощью бесплатной утилиты Process Explorer (от Sysinternals). Достаточно открыть свойства процесса и перейти на вкладку Environment.
The `echo` command in CMD is used to display messages or the value of environment variables in the command prompt.
echo %PATH%
Understanding CMD and Environment Variables
What is CMD?
CMD, short for Command Prompt, is a command-line interpreter in Windows operating systems. It serves as a powerful tool that allows users to execute commands, run scripts, and manage files directly through textual commands. Originating from earlier systems like MS-DOS, CMD remains an essential utility for system administrators, developers, and tech enthusiasts. Its functionality extends from basic operations, such as file management, to advanced scripting capabilities.
What are Environment Variables?
Environment variables are dynamic values that the operating system uses to determine various settings and configurations. Each variable carries specific information about the environment in which your commands run. For instance, the `PATH` variable stores a list of directories that the operating system searches when you run a command. This allows users to execute programs without needing to specify their complete paths.
Some commonly used environment variables include:
- `PATH`: Directories where the system looks for executable files.
- `TEMP`: The path designated for temporary files.
- `USERPROFILE`: The path to the current user’s profile directory.
Understanding and managing environment variables is crucial for effective system operation and command line functionality.
Check Environment Variables in Cmd: A Quick Tutorial
The `echo` Command in CMD
What is the `echo` Command?
The `echo` command is a built-in command in CMD that displays messages and environment variable values to the console. It is a common tool used in scripts and batch files for providing information to users or signaling the outcome of operations.
Syntax of the `echo` Command
The simple syntax for the `echo` command is:
echo [message]
You can provide several options, such as:
- `echo on`: You can enable command echoing.
- `echo off`: You can disable command echoing and suppress command display.
View Environment Variables Cmd with Ease
Using `echo` to Display Environment Variables
Accessing Environment Variables in CMD
Before using the CMD `echo` command for environment variables, you may want to list all available ones. To view all environment variables, simply type:
set
This will present a comprehensive list of all environment variables defined in your session.
Using `echo` to Display a Specific Environment Variable
To display a specific environment variable using the `echo` command, you can reference it with `%` signs surrounding the variable name. For example, to show the value of the `USERPROFILE` variable, you would use:
echo %USERPROFILE%
This command outputs the current user’s profile directory path, showcasing how `echo` effectively pulls and displays environmental settings.
Practical Applications of `echo` with Environment Variables
The versatility of the `echo` command allows it to be used for various practical applications. It can be especially useful in script debugging or showing runtime variable values. For instance, consider the following script snippet that creates a custom variable and displays its value:
@echo off
set MY_VAR=%USERPROFILE%\Documents
echo The document folder is located at: %MY_VAR%
In this example, `MY_VAR` becomes an alias for the documents folder path specific to the user. The script succinctly outputs the directory location, enhancing clarity and understanding of variable utilization.
How to Open Environment Variables from Cmd Easily
Advanced Use Cases of `echo` with Environment Variables
Combining `echo` with Other Commands
The `echo` command can also be effectively combined with other commands to form powerful utility scripts. For instance, consider piping output to files or combining it with the `set` command to verify values:
set MY_ENV_VAR=Hello
echo %MY_ENV_VAR%
In this instance, `MY_ENV_VAR` is assigned the value «Hello,» and `echo` confirms the assignment, facilitating script checks.
Environment Variables in Batch Files
When creating batch files, the power of `echo` becomes even more pronounced. By using `echo` in conjunction with environment variables, you can enlighten users about system settings effortlessly. Below is a simple example of how to leverage these concepts in a batch file:
@echo off
echo Current PATH is: %PATH%
echo User Profile is: %USERPROFILE%
This script provides useful information to the user, making it easier to understand the current system configuration without having to manually check each variable.
Mastering Cmd Set Variable: Quick Guide for Beginners
Troubleshooting Common Issues with `echo` and Environment Variables
Common Errors and Their Solutions
While working with `echo` and environment variables, you may encounter several common issues, such as:
- Undefined Variables: If a variable returns as empty, ensure that it is defined in the current session.
- Incorrect Syntax: Always double-check your syntax, particularly the use of `%` when accessing variable values.
Best Practices for Using `echo` with Environment Variables
To effectively manage environment variables when using `echo`, consider these best practices:
- Clarity in Naming: Use intuitive names for user-defined variables to reduce confusion.
- Avoid Conflicts: Be cautious of defining variables that may override existing system variables. Naming conventions or prefixes can help mitigate conflicts.
- Documentation: Comment on critical parts of scripts to explain what variables represent, ensuring ease of understanding for others reviewing your code.
Exploring Cmd System Variables: A Quick Guide
Conclusion
The combination of the `cmd echo environment variable` provides a robust toolset for both simple and advanced command line operations. Mastering these commands not only enhances your productivity but also deepens your understanding of how your operating system functions. By leveraging `echo` effectively with environment variables, you can greatly improve your ability to manage and utilize system configurations in Windows CMD.
Cmd Echo Current Directory: A Simple Guide
Additional Resources
For further reading, consider checking the official Microsoft documentation on CMD commands, environment variables, and batch scripting techniques. Utilizing forums and community sources can also provide additional insights and tools that support CMD learning and usage.
What is an environment variable in Windows? An environment variable is a dynamic “object” containing an editable value which may be used by one or more software programs in Windows.
In this note i am showing how to list environment variables and display their values from the Windows command-line prompt and from the PowerShell.
Cool Tip: Add a directory to Windows %PATH%
environment variable! Read More →
The environment variables in Windows can be printed using the Windows command-line prompt (CMD) or using the PowerShell.
Windows Command-Line Prompt (CMD)
List all Windows environment variables and their values:
C:\> set
“Echo” the contents of a particular environment variable:
C:\> echo %ENVIRONMENT_VARIABLE%
Windows PowerShell
Print all Windows environment variables (names and values):
PS C:\> gci env:* | sort-object name
Show the contents of a particular environment variable:
PS C:\> echo $env:ENVIRONMENT_VARIABLE
Cool Tip: Set environment variables in Windows! Read More →
Was it useful? Share this post with the world!
Last Updated :
01 Aug, 2022
Environment Variables refer to the variables which are globally declared and can be accessed by the processor under the management of OS like Windows, Mac, and Linux. In starting they were meant to store the path locations but now they also work with Batch Script. The data of batch programs like input from CMD prompt, text files, log files, etc are stored under this. The user can easily change the search path using a batch file so that the applications can be run efficiently. If a variable is undefined and a batch file is scanned, some unwanted execution can occur.
An example is given below:-
@echo off set /p result = Want to say Hello ? (Y/N) ? if /i "%result:~,1%" EQU "Y" echo Hello Ji! if /i "%result:~,1% EQU "N" echo Bye Bye pause
- «Y» input from the user will lead to print hello as mentioned above.
- «N» input from the user will lead to print bye-bye.
Benefits of Environment Variables
- Efficient Execution Performance: It boosts the performance of the batch script so the commands which are executing run in less time and space complexities.
- Make script application secure: Credential information got highly secured after using environment variables
- Reduce Execution mistakes: Runtime execution errors reduces to a large extent after developing environment variables as it configures them properly.
Environment expressions are as follows:
- %name:~n% — It skips the first «n» letters and returns the remaining.
- %name:~n,m% — It skips «n» letters and returns the next «m»
- %name:,m% — Leftmost «m» number of letters.
- %name:~-m% — Rightmost «m» number of letters.
Output Examples of the above expressions:
1.) ECHO %var% :
2.) ECHO %var:~2,3% :
3.) ECHO %var:~-3% :
4.) ECHO %var:~,3% :
5.) ECHO %var:~2%:
Environment variables are key-value pairs a system uses to set up a software environment. The environment variables also play a crucial role in certain installations, such as installing Java on your PC or Raspberry Pi.
In this tutorial, we will cover different ways you can set, list, and unset environment variables in Windows 10.
Prerequisites
- A system running Windows 10
- User account with admin privileges
- Access to the Command Prompt or Windows PowerShell
Check Current Environment Variables
The method for checking current environment variables depends on whether you are using the Command Prompt or Windows PowerShell:
List All Environment Variables
In the Command Prompt, use the following command to list all environment variables:
set
If you are using Windows PowerShell, list all the environment variables with:
Get-ChildItem Env:
Check A Specific Environment Variable
Both the Command Prompt and PowerShell use the echo command to list specific environment variables.
The Command prompt uses the following syntax:
echo %[variable_name]%
In Windows PowerShell, use:
echo $Env:[variable_name]
Here, [variable_name]
is the name of the environment variable you want to check.
Set Environment Variable in Windows via GUI
Follow the steps to set environment variables using the Windows GUI:
1. Press Windows + R to open the Windows Run prompt.
2. Type in sysdm.cpl and click OK.
3. Open the Advanced tab and click on the Environment Variables button in the System Properties window.
4. The Environment Variables window is divided into two sections. The sections display user-specific and system-wide environment variables. To add a variable, click the New… button under the appropriate section.
5. Enter the variable name and value in the New User Variable prompt and click OK.
Set Environment Variable in Windows via Command Prompt
Use the setx
command to set a new user-specific environment variable via the Command Prompt:
setx [variable_name] "[variable_value]"
Where:
[variable_name]
: The name of the environment variable you want to set.[variable_value]
: The value you want to assign to the new environment variable.
For instance:
setx Test_variable "Variable value"
Note: You need to restart the Command Prompt for the changes to take effect.
To add a system-wide environment variable, open the Command Prompt as administrator and use:
setx [variable_name] "[variable_value]" /M
Unset Environment Variables
There are two ways to unset environment variables in Windows:
Unset Environment Variables in Windows via GUI
To unset an environment variable using the GUI, follow the steps in the section on setting environment variables via GUI to reach the Environment Variables window.
In this window:
1. Locate the variable you want to unset in the appropriate section.
2. Click the variable to highlight it.
3. Click the Delete button to unset it.
Unset Environment Variables in Windows via Registry
When you add an environment variable in Windows, the key-value pair is saved in the registry. The default registry folders for environment variables are:
- user-specific variables: HKEY_CURRENT_USEREnvironment
- system-wide variables: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
Using the reg
command allows you to review and unset environment variables directly in the registry.
Note: The reg
command works the same in the Command Prompt and Windows PowerShell.
Use the following command to list all user-specific environment variables:
reg query HKEY_CURRENT_USEREnvironment
List all the system environment variables with:
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment"
If you want to list a specific variable, use:
reg query HKEY_CURRENT_USEREnvironment /v [variable_name]
or
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name]
Where:
/v
: Declares the intent to list a specific variable.[variable_name]
: The name of the environment variable you want to list.
Use the following command to unset an environment variable in the registry:
reg delete HKEY_CURRENT_USEREnvironment /v [variable_name] /f
or
reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name] /f
Note: The /f
parameter is used to confirm the reg delete
command. Without it, entering the command triggers the Delete the registry value EXAMPLE (Yes/No)?
prompt.
Run the setx
command again to propagate the environment variables and confirm the changes to the registry.
Note: If you don’t have any other variables to add with the setx
command, set a throwaway variable. For example:
setx [variable_name] trash
Conclusion
After following this guide, you should know how to set user-specific and system-wide environment variables in Windows 10.
Looking for this tutorial for a different OS? Check out our guides on How to Set Environment Variables in Linux, How to Set Environment Variables in ZSH, and How to Set Environment Variables in MacOS.
Was this article helpful?
YesNo