You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bash的while循环判断中将curl执行结果存储为变量

结论先行

你给出的写法不可行。

不可行的原因

$(curl_output=$(curl test.com/test))属于Bash的命令替换语法,命令替换会启动独立的子shell执行内部命令,你在子shell中赋值的curl_output变量仅在子shell生命周期内有效,主shell的循环体中无法读取到这个变量的值,因此if判断的条件永远不成立。


正确实现方案

利用Bash while 后可接多条命令的特性,把curl赋值操作放在判断逻辑之前,全程仅发起一次curl请求:

while 
    # 先执行curl把结果存入变量,加-s参数开启静默模式避免无关输出
    curl_output=$(curl -s test.com/test)
    # 最后一条命令的退出状态决定循环是否继续
    [[ $curl_output != "true" ]]
do
    if [[ $curl_output == "stopping" ]] ;then
        /etc/shutdown.sh
    else
        sleep "$sleep_timer"
    fi
done

可选优化点

如果需要处理curl请求失败(比如网络波动、域名解析失败)的场景,可以额外加退出码判断:

while 
    curl_output=$(curl -s test.com/test)
    curl_exit_code=$?
    [[ $curl_exit_code -eq 0 && $curl_output != "true" ]]
do
    if [[ $curl_output == "stopping" ]] ;then
        /etc/shutdown.sh
    elif [[ $curl_exit_code -ne 0 ]]; then
        echo "curl请求失败,退出码:$curl_exit_code"
        # 可根据需求选择直接退出脚本或跳过休眠继续重试
        # exit 1
    else
        sleep "$sleep_timer"
    fi
done

内容的提问来源于stack exchange,提问作者SimpleNiko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:06:02