2012-10-24 31 views
1

我想知道是否有可能有一个批处理文件检查自己的字符串。让批处理文件检查自己的输出?

我使用一个批处理文件来运行Maven的命令,我要检查是否有任何通过在脚本的末尾寻找一个“失败”的字符串失败

我知道你可以在其他文件中FIND ,但是你可以让它检查自身的当前输出,还是将批处理文件输出保存为文本然后搜索它的最佳解决方案?

举个例子,如果我有一个批处理文件echo Hello World这将打印Hello World,那么我会想搜索的输出Hello告诉我它找到的字符串Hello

回答

6

我喜欢叶的主意,采取经MVN提供的返回码的动作,但不是使用ERRORLEVEL,我喜欢用||操作。如果先前的命令失败,则仅在||之后执行的命令才会生效。

::initialize error flag to undefined 
set "mvnErr=" 

::run your Maven command and define the error flag if there was an error 
call mvn {your arguments here} || set mvnErr=1 

::You can now take action if there was an error 
if defined mvnErr echo there was a Maven error 
+0

对于更大的批处理文件,这样做有点难以实施,但是比'if errorlevel ...' :-) – Joey

+0

失败并不一定意味着它会抛出任何错误,因为它能够继续。或者maven报告失败是错误? – Johannes

+0

@Johannes - 我从来没有使用过Maven,但是根据我读过的内容,如果构建失败,只要您使用的是2.0.9或更高版本,就应该返回一个积极的错误代码。这似乎是你可以轻松测试自己的东西。 – dbenham

5

您可以通过在每个Maven命令后检查errorlevel来完成此操作。例如

@ECHO OFF 

set hasErrors=0 

REM execute maven command here 
if not errorlevel 0 set hasErrors=1 

REM more batch command and similar checking ... 

if %hasErrors%==1 (
    echo print your error info or do whatever 
) 
+0

是的东西内置到Maven的?跟踪'errorlevel'? – Johannes

+1

@Johannes errorlevel检查不是内置到maven中,而是在完成使用'mvn'执行的命令时设置错误级别。所以'mvn'会将errorlevel设置为0以外的值,如果它有错误的话。 – vane

+1

@Johannes'mvn'将errorlevel设置为1,如果有错误,如果没有错误,则设置为0 – vane

1

为了解决前两个答案,我认为这给了两全其美。在每个命令之前,||语法短小且易于阅读,而IF语句确保只有在以前的操作成功时才​​会进行处理。

set hasErrors=0 
IF %hasErrors%==0 call mvn -f ./mycoservices/pom.xml install || set hasErrors=1 
IF %hasErrors%==0 call mvn -f ./mycostatic/pom.xml install || set hasErrors=1 
IF %hasErrors%==0 call mvn -f ./mycoweb/pom.xml install || set hasErrors=1 
IF %hasErrors%==0 call mvn -f ./mycowebbundle/pom.xml install || set hasErrors=1 
+2

简单但:cmd1 && cmd2 && cmd3 && cmd4 ||设置hasErrors = 1'。如果你愿意,每个'&&'后面使用''''继续''使其更好。 – dbenham

0

为什么不干脆退出批处理时,它会失败

if %ERRORLEVEL% NEQ 0 (
echo exit /b %errorlevel% 
exit /b %errorlevel% 
) 
相关问题