【问题标题】:Better solution to run command inside if?在 if 内部运行命令的更好解决方案?
【发布时间】:2020-04-10 09:51:07
【问题描述】:

我想用 Jenkins API 检查一些东西。上次作业状态if失败,只需重启,每隔x秒检查一次,直到成功。

#!/bin/bash

while ! curl -u admin:xxxxxxxxxxxxxxx http://jenkins.xxxxxxxxxxxxxxx/job/sync/lastBuild/api/json | grep -q 'result":SUCCESS'; do
sleep 5
        if [[ $(curl -u admin:xxxxxxxxxxxxxxx http://jenkins.xxxxxxxxxxxxxxx/job/sync/lastBuild/api/json | grep -q result\":FAILURE) ]]; then
                echo 'build did not succeed, retrying'
                curl -I -u admin:xxxxxxxxxxxxxxx "http://ts.xxxxxxxxxxxxxxx/job/sync/build?token=sync"
                sleep 10
        else
                echo "next round"
        fi
  sleep 10
done

echo 'build succeeded'

主要问题是,我认为如果作业失败不是用if 触发的。

【问题讨论】:

  • 您检查curl 成功的方法听起来很奇怪。我不知道 curl 如何表示失败,但您假设字符串 FAILURE 被发送到 stdout。更可能的反应是错误消息转到 stderr,和/或 curl 设置非零退出代码以表示失败。我建议您查看您的 curl 版本的手册页。
  • ifwhile 使用相同的语法,并且你得到了正确的 while 循环

标签: bash shell jenkins


【解决方案1】:

我不知道 curl 提供什么作为返回码,但我正在使用

command ||
{
    echo "error happened during command"
}

使用许多不同的命令(scp/sftp 等)。

所以,在你的情况下,这将是

curl -u admin:xxxxxxxxxxxxxxx http://jenkins.xxxxxxxxxxxxxxx/job/sync/lastBuild/api/json ||
{
    echo "build did not succeed"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2012-05-08
    • 1970-01-01
    相关资源
    最近更新 更多