if命令

文章参照:http://blog.csdn.net/synior/archive/2010/09/21/5899666.aspx

一、if "参数" == "字符串"  待执行的命令

参数如果等于指定的字符串,则条件成立,运行命令,否则运行下一句。(注意是两个等号)

如if "%1"=="a" format a:

if { %1 }=={ } goto noparms

if { %2 }=={ } goto noparms

二、if exist 文件名  待执行的命令

如果有指定的文件,则条件成立,运行命令,否则运行下一句。

如if exist config.sys edit config.sys

三、if errorlevel / if not errorlevel 数字 

根据返回码和指定的数字进行比较来判断,如果条件成立,运行命令,否则运行下一句。

if errorlevel 2 goto x2  

DOS程序运行时都会返回一个数字给DOS,称为错误码errorlevel或称返回码,常见的返回码为0、1。

更多内容参照《关于if errorlevel 命令

四、if 和else的组合

实例1

if exist test.ini (

echo 存在 test.ini 文件

) else (

echo 不存在 test.ini 文件

)

五、 if defined 存在判断

if defined与if exist用法基本一样,但是if defined比if exist多一个用法,就是用来判断环境变量是否存在。

实例2

@if defined name (

echo name is %name%

) else (

echo name is not initial

)

set name=robin

@if defined name (

echo name is %name%

) else (

            echo name is not initial

)

Pause

六、字符串的比较

if的常规用法只能判断字符串“等于”和“不等于”,而不能判断“大于”,“小于”,或“大于等于”,“小于等于”等。但在启用命令扩展名后我们就可以判断这些了

EQU - 等于

NEQ - 不等于

LSS - 小于

LEQ - 小于或等于

GTR - 大于

GEQ - 大于或等于

对于字母和符号的比较,cmd会先将这些转换成ascii码后比较。我们就可以用来判断字母与字母,字母与数字的大小了,,如a lss b。

if后面加上/i的开关,在字母的比较中就不会区分大小写了,即,a与A是相等的。

在这里,if的其它用法与常规用法均相同。

注意:在默认情况下,cmd命令扩展名是被启用的

实例3:

@echo off

set str0=robin

set str1=hb

@if %str0% EQU %str1% (

echo the two string is the same

) else (

            if %str0% LSS %str1% (

            echo the %str0% is less than %str1%

            ) else (

            echo the %str0% is big than %str1%

            )

)

set str0=Robin

set str1=robin

@echo 如果不忽略大小写:

@if %str0% EQU %str1% (

            echo the string %str0% and %str1% are the same

) else (

            echo the string %str0% and %str1% are not the same

)

@echo 如果忽略大小写

@if /i %str0% EQU %str1% (

            echo the string %str0% and %str1% are the same

) else (

            echo the string %str0% and %str1% are not the same

)

Pause

、 if cmdextversion number判断

if cmdextversion与if errorlevel用法也基本一样,多了一个比较:与命令扩展名有关联的内部版本号比较。这个知道就可以了,基本上没有用。

猜你喜欢

转载自zzc1684.iteye.com/blog/2217021