如何制定批处理脚本if else子句

时间:2015-12-30 09:45:41

标签: batch-processing

我有一个简单的测试告诉我tomcat8是否正在运行。如果找到服务,它只是输出。

net start | find "Tomcat8" > nul 2>&1
if %ERRORLEVEL%==0 echo "Tomcat8 is running"
if %ERRORLEVEL%==1 echo "Tomcat8 not running"

我怎么能真正将它集成到一个函数中,所以我可以先测试tomcat8是否正在运行,如果是 - goto end:,如果没有 - 启动服务?

例如。

1 个答案:

答案 0 :(得分:0)

阅读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 …

  

括号可用于跨多行拆分命令。这个   能够编写更复杂的IF ... ELSE ...命令:

IF EXIST filename.txt (
    Echo deleting filename.txt
    Del filename.txt
 ) ELSE ( 
    Echo The file was not found.
 )
     

使用括号时,CMD shell将展开[read] all   代码块开头的变量,甚至使用这些值   如果变量值刚刚改变了。开启   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"
)