How to remove a set variable on the command line. Classification of environment variables

02/12/15 21.1K

Why is there such chaos in the world? Yes, because the administrator of our system forgot to fulfill his duties. Or I just lost the list of cmd commands from our world. Although this is a somewhat original look at the existing order of things, it nevertheless reflects part of the truth we need: using the command line, you can easily bring order to your computer:

What is the command line

The command line is the simplest tool for managing your computer's operating system. Control occurs using a number of reserved commands and character sets text keyboard without the mouse ( V operating system Windows).

On UNIX-based systems, you can use the mouse when working with the command line.

Some commands came to us from MS-DOS. The command line is also called the console. It is used not only for administering the operating system, but also for managing regular programs. Most often, the most rarely used commands are included in this set of commands.

Advantage cmd applications main commands is that it consumes a minimum amount of system resources. And this is important when emergency situations, when all the computer’s power is, one way or another, involved.

cmd implements the ability to execute and create entire batch files, which are certain order execution of a number of commands (scripts). Thanks to this, they can be used to automate certain tasks ( account management, data archiving and more).

The Windows command shell for manipulating and redirecting commands to certain operating system utilities and tools is the Cmd.exe interpreter. It loads the console and redirects commands in a format that the system understands.

Working with the command line in the Windows operating system

You can call the console in Windows in several ways:


Both methods involve running the console as the current user. That is, with all the rights and restrictions that are imposed on its role in the operating system. For launch cmd with administrator rights, you need to select the program icon in the Start menu and in context menu select the appropriate item:


After running the utility you can get background information about commands and the format for writing them in the console. To do this, enter the help statement and press “Enter”:

Basic commands for working with files and directories

The most frequently used commands are:

  • RENAME – renaming directories and files. Command syntax:

RENAME | REN [drive/path] original file/directory name | final filename
Example: RENAME C:UsershomeDesktoptost.txt test.txt

  • DEL (ERASE) – used to delete files only, not directories. Its syntax is:

DEL | ERASE [processing method] [filename]
Example: Del C:UsershomeDesktoptest.txt/P

By processing method we mean a special flag that allows you to implement a certain condition when deleting a file. In our example, the “P” flag enables the display of a permission dialog for deleting each file:


More details about the possible values ​​of the “processing method” parameter can be found in technical documentation on the Windows operating system.

  • MD – allows you to create a folder at the specified path. Syntax:

MD [drive:] [path]
Example:
MD C:UsershomeDesktoptest1test2

The example will create a subfolder test2 within the test1 folder. If one of the path's root folders does not exist, it will be created too:

  • RD ( RMDIR) – deletion specific folder or all directories in the specified path. Syntax:

RD | RMDIR [process_key] [drive/path]
Example:
rmdir /s C:UsershomeDesktoptest1test2

The example uses the s flag, which will cause the entire branch of directories specified in the path to be deleted. Therefore, you should not use it unnecessarily rmdir command with this processing key.

In the next section, we'll take a closer look at network cmd commands.

Commands for working with the network

The command line allows you to manage not only file system PC, but also his networking opportunities. Part network commands console included a large number of operators to monitor and test the network. The most relevant of them are:

  • ping – the command is used to monitor capabilities network connection PC. To a remote computer a set number of packets are sent and then sent back. The transmission time of packets and the percentage of losses are taken into account. Syntax:

ping [-t] [-a] [-n counter] [-l size] [-f] [-i TTL] [-v type] [-r counter] [-s counter] [(-j host_list | - k node_list)] [-w interval] [target_PC_name]

Example command implementation:
ping example.microsoft.com
ping –w 10000 192.168.239.132

In the last example cmd The ping command sends a request to the recipient with the specified IP address. The waiting interval between packets is 10,000 (10 seconds). By default this parameter is set to 4000:

  • tracert – used to determine the network path to a specified resource by sending a special echo message through the protocol
  • ICMP (Control Message Protocol). After running the command with parameters, a list of all routers through which the message passes is displayed. The first element in the list is the first router on the side of the requested resource.

The cmd command tracer syntax is:
tracert [-d] [-h maximum_hops] [-j node_list] [-w interval] [target_resource_name]
Example implementation:
tracert -d -h 10 microsoft.com

The example traces the route to a specified resource. This increases the speed of the operation due to the use of the d parameter, which prevents the command from attempting to obtain permission to read IP addresses. The number of transitions (jumps) is limited to 10 using set value parameter h. By default, the number of jumps is 30:


shutdown [(-l|-s|-r|-a)] [-f] [-m [\PC_name]] [-t xx] [-c “messages”] [-d[u][p]: xx:yy]
Example:
shutdown /s /t 60 /f /l /m \191.162.1.53

The remote PC (m) with the specified IP address (191.162.1.53) will shut down (s) after 60 seconds (t). This will force you to log out of all applications (f) and the current user's session (l).

Environment variables used in batch (command) files make it possible to avoid specifying absolute paths to directories. For example, if we do not know the letter in advance system disk, we can always use a variable %systemdrive%, which returns the drive letter on which the OS is installed. Also, variables are used to optimize code - a repeatedly repeated parameter (for example, a registry key) can be assigned a short variable and used. This article discusses in detail various techniques for working with variables, as well as ways to change and create new variables. Now let's talk about everything in order.

Classification of environment variables

Summary

Team Windows shell(cmd.exe) is quite powerful tool working with the system. Batch files can automate a fair amount of tasks, which is why they are often used to automatic installation Windows. Skillful use of variables in batch files allows you to solve a wide range of issues. Working with the command shell becomes more efficient and at the same time the code for batch files is simplified. You can find other examples of using variables on the pages of the website or forum. All examples used in this article are taken from the scripts of the participants, for which many thanks to them.

Terminology

Command shell- this is separate software, which provides direct communication between the user and the operating system. Text user interface The command line provides an environment in which applications and utilities With text interface.

cmd.exe- a command interpreter that the Windows OS command shell uses to translate the entered command into a format that the system understands.

Team session can be initiated either by launch cmd.exe, and launch batch file. In other words, the current command shell is created. Accordingly, exiting this shell (for example, finishing a batch file) ends the command session.

User session (user session) begins when the user logs in (log on) and ends when the user logs off (log off).

    Team SET used to view and change environment variables environment in command line Windows. Environment variables are variables whose accepted values ​​characterize the environment in which the current program- ways system files, hardware information, user directories, etc. Environment variable values ​​are generated during the process Windows boot, user registration in the system, when executing individual processes or using a command SET. To view the value assumed by a specific variable, you can use the command:

SET variable
SET PATH- display the value of a variable PATH
To create a new variable or change the value of an existing one, use the command:

SET variable=string

variable- Environment variable name.
line- A character string assigned to the specified variable.

SET MyName=Vasya- set the value of a variable MyName

SET path=C:\progs;%path%- change the value of a variable PATH by adding to the beginning of the line C:\progs

The value accepted by the variable is available for processing in command files by using its name enclosed in percent signs - % . For example, a command to display text on the ECHO display in the form:

ECHO date- will display the word "date" and the command
ECHO %date% will display the value of the variable date, i.e. current date in operating system format.

Team SET without parameters is used to display the current values ​​of environment variables.

ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\Usr\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
COMPUTERNAME=TEST7
ComSpec=C:\windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
HOMEDRIVE=C:
HOMEPATH=\Users\Usr
LOCALAPPDATA=C:\Users\Usr\AppData\Local
LOGONSERVER=\\TEST7
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
Path=C:\windows\system32;C:\windows;
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS; .VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 15 Model 3 Stepping 4, GenuineIntel
PROCESSOR_LEVEL=15
PROCESSOR_REVISION=0304
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\windows\system32\Windows PowerShell\v1.0\Modules\
PUBLIC=C:\Users\Public
SystemDrive=C:
SystemRoot=C:\windows
TEMP=C:\Users\Usr\AppData\Local\Temp
TMP=C:\Users\Usr\AppData\Local\Temp
USERDOMAIN=test7
USERNAME=Usr
USERPROFILE=C:\Users\Usr
windir=C:\windows

In addition to the variables displayed in the list when calling the SET command, there are others whose values ​​change dynamically:

%CD%- takes the value of the current directory.
%DATE%- takes the value of the current date.
%TIME%- takes the value of the current time.
%RANDOM%- meaning random number in the range between 0 and 32767.
%ERRORLEVEL%- the current value of ERRORLEVEL, a special variable that is used as an indication of the result of program execution.
%CMDEXTVERSION% CMD.EXE extended command processing version value.
%CMDCMDLINE%- expands to the original command line that called the shell.

If you specify only part of the name when calling the SET command, a list of variables whose names begin with the specified string will be displayed. For example:

SET U- will display the values ​​of all variables whose names begin with "U".

The SET command supports two additional switches:

SET /A expression

SET /P variable=

The /A switch specifies that the string to the right of the equals sign is a numeric expression whose value is being evaluated. The expression handler is very simple and supports following operations, listed in descending order of priority:

When using any logical or binary operators, you must enclose the expression string in quotation marks. Any non-numeric strings in the expression are treated as environment variable names whose values ​​are converted to numeric form before use. If a variable with the specified name is not defined in the system, a null value is substituted. This allows you to perform arithmetic operations with the values ​​of environment variables, without having to enter % signs to get the values. If SET /A is called from the command line rather than from a batch file, it prints the final value of the expression. The name of the environment variable must appear to the left of any assignment operator. Numeric values are treated as decimals unless preceded by a prefix:

0x- for hexadecimal numbers
0 - For octal numbers.

Example of using prefixes:

SET /A REZ=0xA+012
ECHO %REZ%

In this batch file, the value of the variable is REZ is calculated by adding the number 10 represented in hexadecimal (0xA) and the number 10 represented in octal (012).

The /P switch allows you to set the value of a variable for the input string entered by the user. Shows the specified promptString prompt before reading the entered string. The promptString prompt may be empty. This key allows you to organize a dialogue with the user in a command file:

@ECHO OFF
SET /P NAME=Enter username:
SET /P pass=Enter password:
ECHO Username - %NAME% , Password - %PASS%

In batch files, quite often you need to work with part of the value taken by a variable, for which you use substitution values:

variable:string1=string2- replaces in the received value of the variable line1 on line2

Next batch file uses replacing the dot character with a dash character in the variable value corresponding to the current date:

@ECHO OFF
set tm=%DATE%
ECHO Date1 = %tm%
SET tm=%DATE:.=-%
ECHO Date2 = %tm%

To highlight part of the value taken by a variable, the following construction is used:

variable:~x,y- Where x- the number of skipped characters from the beginning of the line, and y- the number of characters used as the value of the variable.

The following example uses the display of the current time without seconds and fractions of seconds (only the first 5 characters from the standard value of the TIME variable):

@ECHO OFF
set tm=%TIME%
ECHO Time1 = %tm%
SET tm=%TIME:~0.5%
ECHO Time2 = %tm%

If the value y(length) is not specified, then the value of the variable remaining until the end of the line is used. If the value y is negative, then part of the variable value string from the end is used. The previous example can be modified to specify that the time value received is stripped 6 characters from the end:

@ECHO OFF
set tm=%TIME%
ECHO Time1 = %tm%
SET tm=%TIME:~0.-6%
ECHO Time2 = %tm%

It is possible to use the number of skips is not specified, and is used a negative number, then the value received will be part of the variable from the end of the line:

%PATH:~-10%- will extract the last 10 characters of the PATH variable

Null value can be omitted, preserving the substitution format:

%PATH:~0.-2% equivalent %PATH:~,-2%

When using environment variables in batch files, there is certain limitation, associated with the fact that the assigned value remains unchanged when it is modified within a group of commands specified by parentheses, for example in commands IF or FOR. To bypass this limitation launch is used command processor with the /V:ON parameter and instead of percent signs, to obtain the received variable value, use exclamation marks. In addition, it is possible to use standard launch command processor, but with local activation of this mode with the command:

The difference in the results of using variable values ​​is quite clearly demonstrated by the following batch file:


@ECHO OFF
set VAR=before
if "%VAR%" == "before" (
set VAR=after
if "!VAR!" == "after" @echo With percent sign=%VAR% , With question mark=!VAR!

Team set VAR=after executed inside a subroutine delimited by parentheses and, if the command is removed Setlocal EnableDelayedExpansion or not to use to get the value of a variable VAR exclamation marks, its value will remain the old one (what was set before entering the subroutine). A similar problem occurs when the value of a variable is changed within the command loop. FOR. For example, to get a list of files in the current directory, a batch file like this will not work:

set LIST=
for %%i in (*) do set LIST=%LIST% %%i
echo %LIST%

Variable value LIST will not be changed inside the loop. In order for this to happen, the batch file must be modified as follows:

Setlocal EnableDelayedExpansion
set LIST=
for %%i in (*) do set LIST=!LIST! %%i
echo %LIST%

Now, the value of the variable LIST inside a loop FOR will change, sequentially taking on the values ​​of file names separated by space ( set LIST=!LIST! %%i)

The cmd.exe shell environment is defined by variables that control the behavior of the shell and operating system.

It is possible to define the behavior of the shell environment or the entire operating system environment using two types of environment variables: system and local.

System environment variables define the behavior of the global operating system environment, and local environment variables define the behavior of the environment within a given instance of cmd.exe.

System environment variables are set by default in the operating system and are available to everyone Windows processes, and users with administrator privileges can change these variables. These variables are most commonly used in login scripts.

Local environment variables are available when the user for whom they were created is logged in. Local variables from the registry hive HKEY_CURRENT_USER are valid only for the current user, but define the behavior of the global operating system environment.

List of variable types in descending order of priority.

  1. Built-in System Variables
  2. Registry hive system variables HKEY_LOCAL_MACHINE
  3. Local registry hive variables HKEY_CURRENT_USER
  4. All environment variables and paths are listed in the file Autoexec.bat.
  5. All environment variables and paths are specified in the login script (if present).
  6. Variables used interactively in a script or batch file

IN command shell each instance of cmd.exe inherits the environment of its parent application and accordingly, you can change variables in the new cmd.exe environment, which will not affect the environment of the parent application.

Here is a list of system and local environment variables for Windows XP.

Variable

Description

%ALLUSERSPROFILE%

Local

Returns the placement of the "All Users" profile.

Local

Returns the default location of application data.

Local

Returns the path to the current folder.

Local

Returns the command string that was used to launch this instance of Cmd.exe.

System

Returns the version number of the current command processor extensions.

System

Returns the computer name.

System

Returns the path to the command shell being executed.

System

Returns the current data. Uses the same format as the command date/t. Created by the Cmd.exe command.

System

Returns the error code of the last command used. Meaning, no equal to zero, usually indicates that there is an error.

System

Returns the local drive name workstation associated with the user's home directory. Set based on the location of the main directory. The user's home directory is specified in the snap-in " Local users and groups."

System

Returns the full path to the user's home directory. Set based on the location of the main directory. The user's home directory is specified in the Local Users and Groups snap-in.

System

Returns the network path to the user's shared home directory. Set based on the location of the main directory. The user's home directory is specified in the Local Users and Groups snap-in.

Local

Returns the name of the domain controller that authenticated the current session.

%NUMBER_OF_PROCESSORS%

System

Specifies the number of processors installed on the computer.

System

Returns the operating system name. At using Windows 2000 operating system name appears as Windows_NT.

System

Specifies the search path for executable files.

System

Returns a list of file extensions that are considered executable by the operating system.

%PROCESSOR_ARCHITECTURE%

System

Returns the processor architecture. Values: x86, IA64.

%PROCESSOR_IDENTFIER%

System

Returns a description of the processor.

%PROCESSOR_LEVEL%

System

Returns the model number of the processor installed on the computer.

%PROCESSOR_REVISION%

System

Returns the processor revision number.

Local

Returns command line options for the current interpreter. Created by the Cmd.exe command.

System

Returns arbitrary decimal number from 0 to 32767. Created by the Cmd.exe command.

System

Returns the name of the drive containing the Windows XP root directory (that is, the system directory).

System

Returns the location of the Windows XP system directory.

System and user

Returns the default temporary folders used by applications that are accessible to logged-in users. Some applications require the TEMP variable, others require the TMP variable.

System

Returns current time. Uses the same format as the command time/t. Created by the Cmd.exe command.

Local

Returns the name of the domain containing the list of user accounts.

Local

Returns the username of the currently logged in user.

Local

Returns the profile placement for the current user.

System

Returns the location of the operating system directory.

In this article:

  • Defining Variables
  • Command line variables (bat file call parameters)
  • IF Conditional Operator
  • Functions
  • Using return values ​​(processing exit code)

Defining Variables

SET<Имяпеременной>=<Значениепеременной>

The SET statement is an extension of the operating system's options for working with parameters. It specifies a variable whose value is substituted for its name whenever that name is used between percent signs. So, if set (a variable that many games that use sound card computer):

SET BLASTER=A220 I5 D1 P330

then when using the following construction in a batch file:

ECHO %BLASTER%

"A220 I5 D1 P330" will be displayed. Variables defined using the SET statement are called environment variables and are visible after execution until DOS is restarted (unless manually changed in memory). That is, it can be used from one batch file or program after being specified in another. The most famous is PATH variable, which is a set of paths for quick search files. It is set in the autoexec.bat file.

Command Line Variables
(parameters for calling the bat file)

%<цифра 0-9>

As in any language, in the batch file language it is possible to use variables received as parameters of the bat file.

There can be a total of 10 simultaneously existing independent variables. For writing complex programs this is quite small though for regular work Often 3-4 are enough. The value of the variable is equal to the value of the corresponding parameter from the command line. The %0 variable will contain the name of the .bat file and, if you specified it, the path to it. That is, if you ran the abc.bat file with the following parameters:

abc.bat a bc def

then the variable %0 will contain the value abc.bat , %1 will contain the value a , %2 will contain bc , and %3 will contain def . This property is widely used to create versatile batch files when dealing with repetitive operations.

To get more than 10 variables from the command line, you can use the SHIFT command.

The SHIFT command allows you to use more than 10 command line parameters. However, the corresponding earlier parameters are lost. In other words, the SHIFT command shifts all variable values ​​one step to the left. That is, the variable %0 will contain the value previously contained in the variable %1, and the variable %1 will contain the value of the variable %2 before the shift. However, this operation is irreversible, that is, it is impossible to shift the variables back.

IF Conditional Operator

Fortunately, command interpreter cmd.exe in modern Windows 2000 and later supports command blocks in branching constructs, eliminating the need to use IFs with labels. Command blocks are enclosed in parentheses. It looks like this (imitating C/C++ indentation style):

if condition (

Rem Commands of the 'then' branch

Rem...

) else (

Rem Commands of the ‘else’ branch

Rem...

Specific example uses:

@echo off

set BUILDMODE=%1

if "%BUILDMODE%" == "" (

Echo FAIL: Argument is required ^(--debug, --release^)

Exit /b 1

rem Remove all hyphens from the argument to simplify processing

set BUILDMODE=%BUILDMODE:-=%

if "%BUILDMODE%" == "debug" (

Set CCFLAGS=/Od /MDd /Z7

) else (

Set CCFLAGS=/O2 /MD

In my opinion, this is quite possible to live with. But, as always, life is not as simple as it seems. There is one problem. Variables used in then and else blocks are expanded before the blocks begin execution, not during execution. In the example given this does not cause any problems, but in the following it will:

if "%BUILDMODE%" == "debug" (

Echo INFO: Setting the environment debug mode

Set OPTFLAGS=/Od

Set CCFLAGS=%OPTFLAGS% /MDd /Z7

) else (

Echo INFO: Setting the environment release mode

Set OPTFLAGS=/O2

Set CCFLAGS=%OPTFLAGS% /MD

The catch is that in both blocks, the substitution of the OPTFLAGS variable will occur before it is changed during the execution of that block. Accordingly, CCFLAGS will be filled with the value that OPTFLAGS had at the time the execution of this if block began.

This problem is solved by using delayed variable expansion. Variables contained in !…! instead of %...% , their meanings will be revealed only at the moment of direct use. This mode disabled by default. You can enable it either by using the /V:ON switch when calling cmd.exe, or by using the command:

in the text of the bat file itself. The second method seems more convenient to me - it’s not very cool to require someone to run your script with a certain parameter.

With that said, the previous "wrong" example can be corrected like this:

setlocal enabledelayedexpansion

if "%BUILDMODE%" == "debug" (

Echo INFO: Setting up debug mode environment

Set OPTFLAGS=/Od

Set CCFLAGS=!OPTFLAGS! /MDd /Z7

) else (

Echo INFO: Setting up release mode environment

Set OPTFLAGS=/O2

Set CCFLAGS=!OPTFLAGS! /MD

Now this is almost a full-fledged if-then-else block. Almost, because if in one of the echo commands you encounter a closing parenthesis, then you need to escape it with a ^ character, otherwise the parser will get confused...

But in any case, this is much better than the insane number of tags and transitions.

Functions

Is it possible to create a function in a bat file? Yes, you can. Moreover, sometimes it is even necessary. True, these can be called functions conditionally.

There is a special syntax for the call command, which allows you to go to a mark in the same bat file, remembering the place from where this call was made:

call:label arguments

The function is returned with the command:

exit /b [optional return code]

The /b key is very important here: without it, you will exit not the function, but the script in general.

For details, type at the command line:

call/?

exit /?

Interestingly, the call command with this syntax supports recursive calls with automatic creation new frame for variable arguments %0-%9. Sometimes this can be useful. Here is a classic example of recursive factorial calculation in command language:

@echo off

call:factorial %1

echo %RESULT%

exit

rem Function to calculate the factorial value

rem Login:

rem %1 The number for which you want to calculate the factorial

rem Output:

rem %RESULT% Factorial value

:factorial

if %1 == 0 (

Set RESULT=1

Exit /b

if %1 == 1 (

Set RESULT=1

Exit /b

set /a PARAM=%1 - 1

call:factorial %PARAM%

set /a RESULT=%1 * %RESULT%

exit /b

Example of work:

> factorial.bat 10

3628800

Using Return Values
(processing program exit code)

When any program completes its work, it returns its termination code to the operating system. It is customary to return zero upon successful completion, otherwise an error code. Sometimes, or rather often, a program "deliberately" returns a non-zero value so that some details of its operation can be "learned" in the batch file. For example, the program returns the code of the key pressed, and the .bat file performs various actions based on it.

How can a batch file find out the exit code of the executed program? The ERRORLEVEL key variable is provided for this purpose.

Example of a batch file with errorlevels:

@ECHO OFF

REM Run the program prg1.exe

PRG1.EXE

REM Completion code analysis

IF ERRORLEVEL 2 GOTO FILENOTFOUND

IF ERRORLEVEL 1 GOTO WRITEERROR

IF ERRORLEVEL 0 GOTO EXITOK

GOTO ONEXIT

:FILENOTFOUND

ECHO Error! File not found!

GOTO ONEXIT

:WRITEERROR

ECHO Recording error!

GOTO ONEXIT

:EXITOK

ECHO The program was completed successfully.

GOTO ONEXIT

:ONEXIT

Please note that the analysis of the exit code does not start from zero, but from the maximum possible value. The fact is that such a check means: “if errorlevel is greater than or equal to the value, then...”. That is, if we check starting from zero, any value will be true on the first line, which is incorrect.

This is the most common mistake in this kind programs.