繁体   English   中英

Jenkins - If Else 语句未在脚本块中执行

[英]Jenkins - If Else statement not executing in script block

我在 jenkins 脚本部分定义了 If-Else。 但它根本不会被执行。 知道出了什么问题。

script {
    unit_test_result = sh (
        script: ''' #!/bin/bash 
                    mvn clean test | grep \'Tests run:\' | grep -v \'Time elapsed\' 
                    if [[ $? == 1 ]]; 
                        then echo "No Unit tests to run!";
                    fi
                ''',
        returnStdout: true
    ).trim()
}

但是 if 部分根本不运行..

[Pipeline] script
[Pipeline] 
[Pipeline] 
+ grep Tests run:
+ mvn clean test
+ grep -v Time elapsed
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
Failed in branch Unit Tests

grep -v 'Time elapsed'仅在每个输入行不包含Time elapsed以状态代码1退出,但这永远不会发生,因为mvn似乎总是打印摘要。

根据这个网站mvn clean test的output如果有测试的话如下所示

-------------------------------------------------------
T E S T S
-------------------------------------------------------
[...]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.547 sec
[...]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.018 sec

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

根据这个问题,如果没有测试如下

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
There are no tests to run.

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

在这两种情况下, grep 'Tests run:'将至少打印最后一行的摘要。 摘要从不包含Time elapsed 因此grep -v 'Time elapsed'总是以状态码0退出。

请尝试使用以下脚本:

#!/bin/bash
if ! mvn clean test | grep -q '^Tests run: [^0]'; then
    echo "No Unit tests to run!";
fi

对于这个问题中显示的输出,我们可以使用if mvn clean test | grep -Fxq 'There are no tests to run.' if mvn clean test | grep -Fxq 'There are no tests to run.' 反而。 但是我发现mvn没有打印该字符串的其他示例输出; 有时甚至没有总结。 第一个脚本也处理所有这些情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM