If the variable takes the value cmd if. CMD-BAT Features and functions

In this article we will look at conditional operator if command line (CMD). As in any other programming language, conditional statements are used to test a given condition and, depending on the result, perform one or another action.

The cmd if conditional statement contains almost the same syntax as similar constructs VBScript languages(see article “”) and Jscript (article “”) script server.

if statement command line

if condition (statement1)

At the beginning Checking condition, if it is satisfied, the transition goes to the execution of operator1, if not, to operator2. If after the keyword if you write not (if not), then: the condition will be checked, if it is not met, go to operator1, if the condition is met, go to operator2. The use of parentheses is optional, but if you need to execute several cmd if statements at once after checking the condition, then round brackets necessary.

let's open notepad editor++ and write the following code in it:

Here, as before, the parameter passed to the script is checked; if the value is 1, then three commands will be executed sequentially:

  • hostname– displays the computer name
  • ver– displays the OS version
  • ipconfig /all– displays network settings

To execute commands sequentially, we used the concatenation sign “&”. If the condition is not met, the utility will be called netstat.

To check the existence of a variable, the operators are used if defined(if the variable exists) and if not defined (if variable doesn't exist):

@ echo off set Var1 =100 if defined Var1 (echo % Var1% ) set Var1 = if not defined Var1 (echo NOT EXIST!!! Var1)

If you run this code, then two lines will be displayed in the command line window:

100
NOT EXIST!!! Var1

First, the script creates the variable Var1 and assigns it the value 100, then checks: if the variable Var1 exists, print its value. Then we delete the variable and run the check again: if the variable Var1 does not exist, print the line NOT EXIST!!! Var1.

We have the right to use the conditional if statement as a nested one:

@ echo off if "%1" =="1" (@ if "%2" =="2" (hostname & ver) else (ver) ) else (hostname & ver & netstat -a)

IN in this example, the first command line statement if checks whether the first argument is equal to 1, if so, then the second conditional statement is executed and the value of the other argument is checked.

Note!!! All variables are defined as strings. When testing the condition, I enclosed the variable and value names in double quotes, this avoids errors, since parameters or arguments may contain spaces, or the variable may not have a value at all.

Let's now look at this example:

IN in this case, we will transmit the string SLOVO, slovo, SloVo and so on, and the string “slovo” will be displayed on the console screen, since case sensitivity will be disabled.

If statement command line, comparison operators

In addition to the comparison operator “==”, you can use other operators to check a condition:

  • equ"Equals". Returns True if values ​​are equal
  • neq"Not equal". Returns True if values ​​are not equal
  • lss"Less". Returns True if value1 is less than value2
  • lcq"Less or equal". Returns True if value1 is equal to or less than value2
  • gtr"More". Returns True if value1 is greater than value2
  • geq"More or equal". Returns True if value1 is equal to or greater than value2

In this article, we looked at the if command line conditional statement.

You can call another from one batch file by simply specifying its name. For example:

@ECHO OFF CLS REM List log files DIR C:\*.log REM Transfer execution to file f.bat f.bat COPY A:\*.* C:\ PAUSE

However, in this case, after executing the called file, control is not transferred to the calling file, that is, in the example given, the command

(and all commands following it) will never be executed.

In order to call external batch file and then returning to the original file, you need to use special team CALL file

For example:

@ECHO OFF CLS REM List log files DIR C:\*.log REM Transfer execution to file f.bat CALL f.bat COPY A:\*.* C:\ PAUSE

In this case, after the f.bat file is completed, control will return to the original file on the line following the CALL command (in our example, this is the COPY A:\*.* C:\ command).

Jump Operators

The batch file may contain labels and GOTO commands to jump to these labels. Any line starting with a colon: is treated as a label when processing the batch file. The label name is specified by the set of characters following the colon until the first space or the end of the line. Let's give an example.

Let there be a batch file with the following content:

@ECHO OFF COPY %1 %2 GOTO Label1 ECHO This line will never be executed:Label1 REM Continue execution DIR %2

After we get to the command in this file

its execution continues from the line

REM Continue execution

In a GOTO file command, you can specify a :EOF string as the jump label, which transfers control to the end of the current batch file (this allows you to easily exit the batch file without defining any markers at the very end).

Also, to go to a label inside the current command file, in addition to the GOTO command, you can also use the CALL command discussed above:

CALL:argument label

When such a command is called, a new context of the current batch file is created with the given arguments, and control is transferred to the instruction located immediately after the label. To exit such a batch file, you must reach the end of it twice. The first exit returns control to the instruction immediately following the CALL line, and the second exit terminates execution of the batch file. For example, if you run a batch file with the following content with the "Copy-1" parameter:

@ECHO OFF ECHO %1 CALL:2 Copy-2:2 ECHO %1

then three lines will be displayed on the screen:

Copy-1 Copy-2 Copy-1

So this use of the CALL command is very similar to normal call subroutines (procedures) in algorithmic programming languages.

Conditional operators

Using the IF...ELSE command (ELSE keyword may not be present) in batch files You can process multiple types of conditions. Moreover, if the condition specified after IF evaluates to true, the system executes the command (or several commands enclosed in parentheses) following the condition, otherwise the command (or several commands in parentheses) following the condition is executed. keyword ELSE.

Checking the value of a variable

The first type of condition is usually used to check the value of a variable. There are two syntax options for the IF command to do this:

IF line1==line2 command1

(square brackets indicate that the parameters contained in them are optional) or

IF line1 comparison_operator line2 command

Let's look at the first option first. The condition line1==line2 (here you need to write exactly two equal signs) is considered true when exact match both lines. The NOT parameter indicates that given command is executed only if the compared strings do not match.

Strings can be literal or represent variable values ​​(for example, %1 or %TEMP% ). Quotes are not required for literal strings. For example,

IF %1==%2 ECHO Parameters match! IF %1==Petya ECHO Hello, Petya!

Note that some caution should be exercised when comparing strings defined by variables. The fact is that the value of the variable may turn out to be an empty string, and then a situation may arise in which the execution of the batch file will terminate abnormally. For example, if you did not define the variable MyVar using the SET command, and the file contains a conditional statement like

IF %MyVar%==C:\ ECHO Hurray!!!

then during execution it will be substituted for %MyVar% empty line and there will be syntax error. The same situation may occur if one of the strings being compared is the value of a command line parameter, since that parameter may not be specified when the command file is run. Therefore, when comparing strings, you need to append some symbol to them at the beginning, for example:

IF -%MyVar%==-C:\ ECHO Hurray!!!

Using the IF and SHIFT commands, you can loop through all the command line parameters of a file, even without knowing their number in advance. For example, the following batch file (let's call it primer.bat) displays the name of the file to be launched and all the command line options:

@ECHO OFF ECHO Executing file: %0 ECHO. ECHO The file is launched with the following parameters... REM Start of loop:BegLoop IF -%1==- GOTO ExitLoop ECHO %1 REM Shift parameters SHIFT REM Go to the beginning of loop GOTO BegLoop:ExitLoop REM Exit loop ECHO. ECHO All.

If you run primer.bat with four parameters:

primer.bat A B C D

then as a result of execution the following information will be displayed on the screen.

Processing conditions in batch programs.

Syntax

if [not] errorlevel number team [else expression]

if [not] line1== line2 team [else expression]

if [not] exist file name team [else expression]

If extensions command processor are allowed, the following syntax should be used:

if [/i] line1 op_comparison line2 team [else expression]

if cmdextversion number team [else expression]

if defined variable team [else expression]

Options

not Specifies that the command will only be executed if the condition is not met. errorlevel number The condition is true if the previous command processed by the Cmd.exe command interpreter completed with a code equal to or greater than numbers. line1== line2 command The command that should be processed if the condition is met. line1 The condition is satisfied if the lines line2 And %1 match up. Strings can be set explicitly or can be batch variables (for example, exist file name The condition is true if there is a file named file name. comparison_op Three-digit comparison operator. The following table lists op_comparison valid values /i. /i Compare strings without taking into account the case of characters. Parameter== can be used in construction string1 if string2 line1 teams line2. These comparisons are general. If cmdextversion number, And numbers consist of digits, the strings are converted to numbers and a comparison of the numbers is performed. cmdextversion The condition is true only if the internal version number associated with Cmd.exe shell extensions is equal to or greater than defined variable. the first version was number 1. The version number increases by 1 when significant changes are made to shell extensions. Condition with variable fails if shell extensions are disabled (they are enabled by default). else The condition is satisfied if

determined.

  • expression Command and all its parameters for processing on the command line when executing the statement if. if/? else Display help on the command line.
  • Notes errorlevel If the condition specified in the command
  • , is executed, the command following the condition will be executed. If the condition is not met, the command specified in the statement defined variable

    , is skipped, and control passes to the operator’s command defined variable, if it is specified. When the program exits, it returns an exit code. Using the parameter, exit codes can be used as conditions. The condition is satisfied if the lines Using the command.

    When the program exits, it returns an exit code. Using the parameter errorlevel When using the command the following three variables are added:%errorlevel% errorlevel%cmdcmdline% %cmdextversion%:

    , unless it already exists
    environment variable
    with the name ERRORLEVEL. In this case, its value will be used. The following example shows the use of the value
    after execution
    batch program
    goto answer%errorlevel%
    :answer0
    echo Program return code is 0

    :answer1 op_comparison echo Program return code is 1

    goto end

    exit codes can be used as conditions.:end echo Done! Comparison Operators can also be used like this: If %errorlevel% LEQ 1 goto okay can also be used like this:.

    Using the command is replaced by the original one cmdextversion command line

  • passed to Cmd.exe before it is processed by Cmd.exe, unless there is already an environment variable named else

    cmdcmdline else. In this case the value will be used if replaced by a string representation of the current value

    unless there is already an environment variable named CMDEXTVERSION. In this case, its value will be used.

    Using the operator Operator must be placed on the same line as the command:

    IF EXIST filename. del filename. ELSE echo filename. absent

    The example below will not work because the command else must be on the same line as the command if:

    IF EXIST filename. del filename. ELSE echo filename. absent

    If you need to put the entire statement on one line, you can use the following correct form of the original statement:

    IF EXIST filename (del filename) ELSE echo filename is missing

Examples

If the Product.dat file cannot be found, the following message appears:

if not exist product.dat echo Data file not found

In the example below, if an error occurs while formatting the disk in drive A, an error message will be displayed:

:begin
@echo off
format a: /s
if not errorlevel 1 goto end
echo Formatting error.
:answer0
echo End of batch program.

If no error occurs, no error message will be displayed.

Team if cannot be used directly to check the existence of a directory, but a device (NUL) exists in each directory. Therefore, the existence of a directory can be checked as shown below. The following example checks for the existence of a directory:

if exist c:mydir\nul goto process

For questions, discussions, comments, suggestions, etc., you can use the forum section of this site (registration required).

Processing Conditions in Batch Programs

Syntax

if [not] errorlevel number team [else expression]

if [not] line1== line2 team [else expression]

if [not] exist file name team [else expression]

If shell extensions are enabled, the following syntax should be used:

if [/i] line1 op_comparison line2 team [else expression]

if cmdextversion number team [else expression]

if defined variable team [else expression]

Options

not Specifies that the command will only be executed if the condition is not met. errorlevelnumber The condition is true if the previous command processed by the Cmd.exe command interpreter completed with a code equal to or greater than numbers. line1== line2 command The command that should be processed if the condition is met. line1 The condition is satisfied if the lines line2 And %1 match up. Strings can be set explicitly or can be batch variables (for example, existfile name The condition is true if there is a file named file name. op_comparison.

comparison_op Three-digit comparison operator. The following table lists the valid values /i. /i Compare strings without taking into account the case of characters. Parameter== can be used in construction string1 if string2 line1 teams line2. These comparisons are general. If cmdextversion number, And numbers consist of digits, the strings are converted to numbers and a comparison of the numbers is performed. cmdextversion The condition is true only if the internal version number associated with Cmd.exe shell extensions is equal to or greater than defined variable. the first version was number 1. The version number increases by 1 when significant changes are made to shell extensions. Condition with variable fails if shell extensions are disabled (they are enabled by default). else The condition is satisfied if

determined.

  • expression Command and all its parameters for processing on the command line when executing the statement if. if/? else Display help on the command line.
  • Notes errorlevel If the condition specified in the command
  • , is executed, the command following the condition will be executed. If the condition is not met, the command specified in the statement defined variable

    , is skipped, and control passes to the operator’s command defined variable, if it is specified. When the program exits, it returns an exit code. Using the parameter, exit codes can be used as conditions. The condition is satisfied if the lines Using the command.

    When the program exits, it returns an exit code. Using the parameter errorlevel/i Compare strings without taking into account the case of characters. Parameter errorlevel unless there is already an environment variable named ERRORLEVEL. In this case, its value will be used. The following example shows the use of the value

    after executing the batch program:

    :answer1 op_comparison echo Program return code is 1

    goto answer%errorlevel% :answer0 echo Program return code is 0:answer1 echo Program return code is 1 goto end:end echo Done!

    exit codes can be used as conditions. if %errorlevel% LEQ 1 goto okay can also be used like this: If %errorlevel% LEQ 1 goto okay can also be used like this:.

    Using the command is replaced by the original one cmdextversion command line

  • passed to Cmd.exe before it is processed by Cmd.exe, unless there is already an environment variable named else

    cmdcmdline else. In this case the value will be used if is replaced by the original command line passed to Cmd.exe before it is processed by Cmd.exe, unless there is already an environment variable named

    .

    Using the operator Example:

    IF EXIST filename. del filename. ELSE echo filename. absent

    The example below will not work because the command else must be on the same line as the command if:

    IF EXIST filename. (del filename.) ELSE (echo filename. missing.)

    If you need to put the entire statement on one line, you can use the following correct form of the original statement:

    IF EXIST filename (del filename) ELSE echo filename is missing

Examples

If the Product.dat file cannot be found, the following message appears:

if not exist product.dat echo Data file not found

In the example below, if an error occurs while formatting the disk in drive A, an error message will be displayed:

must end with a new line:

If no error occurs, no error message will be displayed.

Team if cannot be used directly to check the existence of a directory, but a device (NUL) exists in each directory. Therefore, the existence of a directory can be checked as shown below. The following example checks for the existence of a directory:

if exist c:mydir\nul goto process

Processing conditions in batch programs.

Syntax

if [not] errorlevel number team [else expression]

if [not] line1== line2 team [else expression]

if [not] exist file name team [else expression]

If shell extensions are enabled, the following syntax should be used:

if [/i] line1 op_comparison line2 team [else expression]

if cmdextversion number team [else expression]

if defined variable team [else expression]

Options

not Specifies that the command will only be executed if the condition is not met. errorlevel number The condition is true if the previous command processed by the Cmd.exe command interpreter completed with a code equal to or greater than numbers. line1== line2 command The command that should be processed if the condition is met. line1 The condition is satisfied if the lines line2 And %1 match up. Strings can be set explicitly or can be batch variables (for example, exist file name The condition is true if there is a file named file name. op_comparison valid values /i. /i Compare strings without taking into account the case of characters. Parameter== can be used in construction string1 if string2 line1 teams line2. These comparisons are general. If cmdextversion number, And numbers consist of digits, the strings are converted to numbers and a comparison of the numbers is performed. cmdextversion The condition is true only if the internal version number associated with Cmd.exe shell extensions is equal to or greater than defined variable. the first version was number 1. The version number increases by 1 when significant changes are made to shell extensions. Condition with variable fails if shell extensions are disabled (they are enabled by default). else The condition is satisfied if

determined.

  • expression Command and all its parameters for processing on the command line when executing the statement if. if/? else Display help on the command line.
  • Notes errorlevel If the condition specified in the command
  • , is executed, the command following the condition will be executed. If the condition is not met, the command specified in the statement defined variable

    , is skipped, and control passes to the operator’s command defined variable, if it is specified. When the program exits, it returns an exit code. Using the parameter, exit codes can be used as conditions. The condition is satisfied if the lines Using the command.

    When the program exits, it returns an exit code. Using the parameter errorlevel/i Compare strings without taking into account the case of characters. Parameter errorlevel unless there is already an environment variable named ERRORLEVEL. In this case, its value will be used. The following example shows the use of the value

    , unless it already exists
    environment variable
    with the name ERRORLEVEL. In this case, its value will be used. The following example shows the use of the value
    after execution
    batch program
    goto answer%errorlevel%
    :answer0
    echo Program return code is 0

    :answer1 op_comparison echo Program return code is 1

    goto end

    exit codes can be used as conditions. if %errorlevel% LEQ 1 goto okay can also be used like this: If %errorlevel% LEQ 1 goto okay can also be used like this:.

    Using the command is replaced by the original one cmdextversion command line

  • passed to Cmd.exe before it is processed by Cmd.exe, unless there is already an environment variable named else

    cmdcmdline else. In this case the value will be used if replaced by a string representation of the current value

    unless there is already an environment variable named CMDEXTVERSION. In this case, its value will be used.

    Using the operator Example:

    IF EXIST filename. del filename. ELSE echo filename. absent

    The example below will not work because the command else must be on the same line as the command if:

    IF EXIST filename. del filename. ELSE echo filename. absent

    If you need to put the entire statement on one line, you can use the following correct form of the original statement:

    IF EXIST filename (del filename) ELSE echo filename is missing

Examples

If the Product.dat file cannot be found, the following message appears:

if not exist product.dat echo Data file not found

In the example below, if an error occurs while formatting the disk in drive A, an error message will be displayed:

:begin
@echo off
format a: /s
if not errorlevel 1 goto end
echo Formatting error.
:answer0
echo End of batch program.

If no error occurs, no error message will be displayed.

Team if cannot be used directly to check the existence of a directory, but a device (NUL) exists in each directory. Therefore, the existence of a directory can be checked as shown below. The following example checks for the existence of a directory:

if exist c:mydir\nul goto process