仅当状态不是200时,Bash curl才会调用第二个命令

时间:2018-03-31 13:54:07

标签: bash curl

我正在寻找解决方案如何在bash中组合两个curl请求,并且仅在第一个不返回状态200时调用第二个curl。

我试过了:

curl -s "https://example.com/first" || curl -s "https://example.com/second"

但它仍会调用两者,因为如果返回例如状态404,则第一次卷曲成功。

只有在第一次没有返回状态200时才能调用秒?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

curl -s -o /dev/null -w "%{http_code}" https://example.com | grep -q "^200$" || curl -s https://example.com/2.html

编辑:@tripleee增加了改进,不会使用grep输出污染输出。

答案 1 :(得分:-1)

最后一个命令的退出代码存储为$?。然后你可以做

curl -s "https://example.com/first"
if [ $? -ne 200 ]; then
    curl -s "https://example.com/second"
fi

或者如果你喜欢单行,

curl -s "https://example.com/first"; [ $? -ne 200 ] && curl -s "https://example.com/second"