Use several advanced commands of DOS batch file to judge

Time:2022-1-9

If , goto , choice , for is a relatively advanced command in batch files. If you are skilled in using these commands, you are an expert in batch files.  

If , indicates that it will judge whether the specified conditions are met, so as to decide to execute different commands. There are three formats:
1. If “parameter” = = “string” command to be executed
If the parameter is equal to the specified string, the condition is true, run the command, otherwise run the next sentence. (note the two equal signs)
For example, if “% 1” = = “a” format a:

2. If # exist # file name # command to be executed
If there is a specified file, the condition is true, run the command, otherwise run the next sentence. For example, if exist config sys edit config. sys 

3. If # errorlevel # number # command to be executed
If the return code is equal to the specified number, the condition is true, run the command, otherwise run the next sentence. For example, if # errorlevel # 2 # goto # X2, when the DOS program runs, it will return a number to DOS, which is called error code errorlevel or return code

Goto # batch files run here will jump to the label specified by goto # and are generally used with if. For example:

goto end 

:end 
echo this is the end 

Label: represented by string , the line where the label is located will not be executed

Choice this command allows the user to enter a character to run different commands. The / C: parameter should be added when using, and the characters prompted for input should be written after C: without spaces. Its return code is 1234

For example: choice / C: DME, defrag, MEM, end
Will show
defrag,mem,end[D,M,E]? 

For example, test The contents of bat are as follows:
@echo off 
choice /c:dme defrag,mem,end 
If # errorlevel # 3 # goto # defrag # judge the error code with the highest value first
if errorlevel 2 goto mem 
if errotlevel 1 goto end 

:defrag 
c:\dos\defrag 
goto end 

:mem 
mem 
goto end 

:end 
echo good bye 

After this file is run, it will display “defrag, MEM, end [D, m, e]”? The user can select d ^ m ^ e, and then the if statement will make a judgment. D means to execute the program segment labeled defrag, m means to execute the program segment labeled MEM, and e means to execute the program segment labeled end. Finally, each program segment jumps the program to the end label with goto ^ end, and then the program will display good ^ bye and the file ends.