【问题标题】:Trying to capture stdout of background process in bash script试图在 bash 脚本中捕获后台进程的标准输出
【发布时间】:2013-06-24 19:30:29
【问题描述】:

我编写了以下内容以与 Jenkins 一起使用来启动我的 selenium 测试。现在,由于它们是作为后台进程执行的,所以当它们失败时,詹金斯认为它们没有。正如您所看到的,我在进行这项工作方面的尝试是徒劳的。有任何想法吗?考虑将输出管道传输到文件中并搜索关键字。然后我意识到如果字符串的 grep 返回 true,我不知道如何反映错误。

#!/bin/bash

FAIL=0


echo "starting"


ruby /root/selenium-tests/test/test1.rb &   
ruby /root/selenium-tests/test/test2.rb & 
ruby /root/selenium-tests/test/test3.rb & 

#wait

for job in `jobs -p`
do
    echo $job
    wait $job || let "FAIL+=1"
done

echo $FAIL

if [ "$FAIL" == "0" ];
then

   echo  "PASS"

else

    echo "FAIL! ($FAIL)"

fi

【问题讨论】:

    标签: bash jenkins


    【解决方案1】:

    Jenkins 最有可能查看进程退出代码以确定测试是否失败。这是所有 Unix 工具所做的。

    有多种方法可以做到这一点。如果您的测试文件输出类似“FAIL”而不是正确返回退出代码,您可以这样做:

    #!/bin/bash
    (
      ruby /root/selenium-tests/test/test1.rb &   
      ruby /root/selenium-tests/test/test2.rb & 
      ruby /root/selenium-tests/test/test3.rb & 
      wait
    ) > log
    
    ! grep "FAIL" log
    exit $?  # <- happens implicitly at the end of the script, and can be left out
    

    在这种情况下,grep 找到“FAIL”会导致脚本失败,Jenkins 会检测到失败。

    如果您的脚本返回正确的退出代码,更正确的方法是您的方法,但不依赖作业控制(默认情况下在非交互式 shell 中关闭),并返回正确的退出代码:

    for test in /root/selenium-tests/test/test*.rb
    do
        ruby "$test" &
        pids+=( $! )
    done
    
    for pid in "${pids[@]}"
    do
        if wait $pid
        then
            echo "$pid succeeded"
        else
            echo "$pid failed"
            (( failures++ ))
        fi
    done
    
    if [[ $failures -gt 0 ]]
    then
        echo "FAIL: $failures failed tests"
        exit 1  # return failure
    else
        echo "PASS!"
        exit 0  # return success
    fi
    

    【讨论】:

    • 谢谢!这解决了我的问题,并在此过程中学到了很多东西。
    猜你喜欢
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    相关资源
    最近更新 更多