阅读if /?
:
%ERRORLEVEL%
将业务拓展到ERRORLEVEL
当前 值的字符串表示,只要有尚未名为ERRORLEVEL
的 环境变量,在这种情况下,你 会得到它的价值。运行程序后,以下 示出ERRORLEVEL
使用:
goto answer%ERRORLEVEL%
:answer0
echo Program had return code 0
:answer1
echo Program had return code 1
不幸的是,上面的代码片段似乎是一个位的情况下errorlevel 0
两个消息混乱作为显示器。尝试下(与find
return codes组合):
net start | find "Tomcat8" > nul 2>&1
goto answer%ERRORLEVEL%
:answer0
echo `find` had return code 0, Tomcat8 is running
goto :acorp
:answer1
echo `find` had return code 1, Tomcat8 not running
rem code snippet to start the service here
goto :acorp
:answer2
rem dummy/debugging
echo `find` had return code 2: invalid switch is given
pause
:acorp
Another approach: IF… ELSE …
圆括号可用于拆分到多个行命令。这 允许的写作更复杂的... ELSE ...命令:
IF EXIST filename.txt (
Echo deleting filename.txt
Del filename.txt
) ELSE (
Echo The file was not found.
)
当使用括号中的CMD
shell将依次展开[阅读]所有 变量的代码块的开始,并使用这些值甚至 如果变量价值刚刚改变。打开 DelayedExpansion将强制shell读取每行开头的变量 。
net start | find "Tomcat8" > nul 2>&1
if %ERRORLEVEL%==1 (
echo "Tomcat8 not running"
rem code snippet to start the service here
) else (
echo "Tomcat8 is running"
)