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

求基于HTTP请求响应执行命令的Linux终端单行命令

解决方案

直接使用以下单行bash命令即可实现需求:

response=$(curl -s http://localhost); if [[ -z "$response" || "$response" -eq 0 ]]; then exit 1; fi

命令解释

  • response=$(curl -s http://localhost):通过curl -s(静默模式,不输出进度/错误信息)请求目标API,将返回结果存入response变量
  • [[ -z "$response" ]]:判断变量是否为空字符串,对应服务器宕机、请求无响应的场景
  • || "$response" -eq 0:逻辑或,判断API返回值是否为0
  • 若满足上述任一条件,执行exit 1终止当前shell进程;若返回1或更大整数,则无任何操作

补充说明

如果需要同时捕获curl请求本身的错误(比如连接超时、拒绝连接等,这类场景下curl会返回非零退出码,但可能输出空字符串),可以调整命令加入curl的状态判断:

response=$(curl -s http://localhost); if [[ $? -ne 0 || -z "$response" || "$response" -eq 0 ]]; then exit 1; fi

这里$?是上一条命令(curl)的退出码,$? -ne 0表示curl请求本身失败,此时也触发exit 1。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:10:45