DOS Batch Advanced Tutorial Sixth Chapter if command to explain _dos/bat

Source: Internet
Author: User
Tags comparison file copy goto

Start Now:

In cmd use if/? Open if system help (see for yourself I am not all listed), we will find that if there are 3 basic usage!
Perform conditional processing in a batch program.

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command

NOT specifies that Windows XP should execute the command only if the condition is false.

ERRORLEVEL number specifies that the condition is true if the last program that is running returns an exit encoding that is equal to or greater than the specified digit.
String1==string2 if the specified text string matches, the specified condition is true.
EXIST filename If the specified filename exists, the specified condition is true.

command specifies the commands to be executed if the condition is met. If the specified condition is FALSE, the command can be followed by an else command that executes the command after the Else keyword.

The ELSE clause must appear on the same line after the IF. For example:

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


First usage: IF [NOT] ERRORLEVEL number command

The basic use of this usage is to determine the code of the previous command execution result to determine the next step.
Generally, the execution result code of the previous command has only two results, and "success" in 0 means "failure" is represented by 1.

As an example:

@echo
off net user
IF%errorlevel% = 0 echo net user execution succeeded!
Pause

This is a simple way to determine whether the previous command succeeded.

A careful friend may find that this usage is not the same as the usage in the help, according to the wording in the help "IF%errorlevel% = 0 echo net user execution succeeded!" "This code should be written: IF ERRORLEVEL 0 echo net user execution succeeded!"

Then why do I have to write this? After you get rid of the code, you'll find it wrong! With this syntax, whether or not your above command succeeds, he will think that the command succeeded, do not know whether the bug or I understand the error ...

Add: This is not a bug, but a feature of the IF ERRORLEVEL statement: When using the IF errorlevel 0 ... Sentence, it means that if the value of the error code is greater than or equal to 0, an action will be performed; When using the If%errorlevel%==0 ... Sentence, it means that if the value of the error code equals 0, an action is performed. Because of the difference in the meaning of the two sentences, if the previous sentence pattern is used, the order of the error code statements is from large to small arrangement

%errorlevel% This is a system variable that returns the execution result code for the previous command! "Success" in 0 means "failure" is represented by 1. Of course, there are other parameters, when used basically the two numbers.
Generally, the execution result code of the previous command has only two results, and "success" in 0 means "failed" in 1.

This is only a general case, in fact, the ERRORLEVEL return value can be between 0~255, for example, xcopy default ERRORLEVEL value of 5, respectively, representing 5 kinds of execution state:

Exit code Description
0 file copy no errors.
1 if errorlevel 2 echo.
2 users terminated xcopy by pressing CTRL + C.
4 An initialization error occurred. There is not enough memory or disk space, or an invalid drive name or syntax was entered on the command line.
5 A disk write error has occurred.

To determine the 5 exits of the above xcopy command, write:
A disk write error occurred if errorlevel 5 echo
An initialization error occurred if errorlevel 4 echo
if errorlevel 2 echo user presses CTRL + C to terminate Xcopy
if errorlevel 1 echo if errorlevel 2 echo
if errorlevel 0 echo File replication has no errors.
To perform correctly.

The supplement is complete.

A few more examples for beginners to understand

@echo
off net usertest
IF%errorlevel% = 1 echo net user execution failed!
Pause

This is to determine whether the last command failed to execute

@echo
off set/p var= arbitrarily enter a command:
%var%
If%errorlevel% = 0 goto Yes
goto no
: Yes
echo!var! executed successfully C11/>pause
exit
: No
echo basically failed to execute.
Pause

This is based on the command you entered, automatic judgment is a success or failure!

In a simplified version of the

@echo off
set/p var= Enter a random command:
%var%
if%errorlevel% = = 0 (echo%var% execution succeeded) ELSE Echo%var% failed!
Pause

Else write the operation after the failed execution!

Of course, I can also put if else such a statement into several lines to write out, so that he looks good point ...

@echo
off set/p var= arbitrarily enter a command:
%var%
if%errorlevel% = = 0 (
  echo!var! execution succeeded
  ) ELSE (
  Echo is basically missing Defeated ...
  )
Pause

The three syntaxes of the two abbreviations that are described here can be applied, not just in the case of the IF [not] ERRORLEVEL number command.

Second usage: IF [not] string1==string2 command

This is used to compare variables or the value of a character is not equal.

Example

@echo off
set/p var= Enter the first comparison character:
set/p var2= Enter a second comparison character:
if%var% = =%var2% (echo we are equal) ELSE echo we are not equal 
   pause

The above example can be used to determine if the value you entered is equal, but if you enter the same character, but if one of the following spaces is played,
This example will still be considered equal, how to make the input of the space is not equal? We can add a double quote on the comparison character.

@echo off
set/p var= Enter the first comparison character:
set/p var2= Please enter the second comparison character (try the Extra space):
if "%var%" = "%var2%" (echo US equals) ELSE Ech o We are not equal
pause

Third usage: IF [NOT] EXIST filename command

This is the syntax to determine whether a file or folder exists

Example

@echo off
if exist "C:\Test" (Echo Presence file) ELSE echo does not exist file
pause

The file path to judge is quoted in order to prevent the path from having spaces, if the path has a space plus a double quotation mark will not appear to judge Error!

There is not much use in this grammar, basically it is so, do not introduce more.

And what does it mean to have a [not] statement after each of the if usages? The other adds his words, the first judge our condition is not tenable, did not add he is the default is to judge when the condition is established, such as the above example

@echo off
if not exist "c:\test" (Echo Presence file) ELSE echo does not exist file
pause

Add a not, after the implementation of what the results, if you do not have c:\test in C, he will still show "presence of files", which means that the addition of not will be judged by the failure of the condition! Understand, the above example changed to this is correct!

@echo off
if not exist "C:\Test" (Echo does not exist file) ELSE echo exists
pause

Fourth usage: If enhanced usage

IF [i] string1 compare-op string2 command #参数/I indicates case insensitive
IF cmdextversion number Command
IF DEFINED variable command #判断变量是否存在, useful

The cmdextversion condition works just like ERRORLEVEL, except that it is compared to the build number associated with the command extension. The first version is 1. The version number is incremented each time the command extension is significantly enhanced. The cmdextversion condition is not true if the command extension is disabled.

If you have defined an environment variable, the DEFINED condition is the same as the EXISTS
IF DEFINED Variable Command
IF not "variable" = "" command
The above two commands have the same effect.

Use the "Set variable=" command to make the variable variable undefined, that is, a null value.

In a word, the variable value is NULL, the value is undefined;
If you use the statement if DEFINED variable command to determine whether a variable exists, be aware that variable is a variable name that does not use the boot symbol%, cannot be written as%variable%, or an error occurs.

Cases:
If defined AA (echo variable AA exists) Else (echo variable AA does not exist)
Run display: variable AA does not exist

Cases:
Set aa=123
Set aa=
If defined AA (echo variable AA exists) Else (echo variable AA does not exist)
Run display: variable AA does not exist


Cases:

@echo off
if a = = A (echo we are equal) ELSE echo we are not equal
pause

Execution will show: we are not equal

Cases:

@echo off
if/i a = = A (echo we are equal) ELSE echo we are not equal
pause

Plus/I is equal to case-insensitive!

Finally, there are symbols for judging numbers.

EQU-equals
NEQ-Not equal to
LSS-Less than
Leq-less than or equal to
GTR-Greater than
GEQ-greater than or equal to

Let me give you an example, everyone knows math ... No more talking.

@echo off
set/p var= Please enter a number:
if%var% leq 4 (Echo I is less than or equal to 4) ELSE echo I am not less than or equal to 4
pause

The above is the introduction of the IF command, we practice more

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.