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

Bash脚本问题:如何正确提取并格式化输出日出日落时间

解决Bash脚本提取日出日落时间的问题

错误分析

  • 变量赋值语法错误:=前后不能有空格,原代码中SUNSET= cut ...会被bash解析为临时设置SUNSET为空环境变量,然后执行cut命令,导致变量未被正确赋值。
  • 未使用命令替换:要将命令输出赋值给变量,必须用$(command)或反引号包裹命令,否则无法捕获输出。
  • cut提取不可靠:依赖固定字符位置提取JSON内容,一旦API返回的JSON结构有微小变化(如空格、字段顺序调整),提取结果就会失效。

解决方法

方法1:修复原有cut写法(仅适配当前JSON结构,不推荐长期使用)

#!/bin/bash
# URL需加双引号,避免&被bash解析为后台执行符号
curl -o test.txt "https://api.sunrise-sunset.org/json?lat=48.813875&lng=2.392521"
# 用命令替换捕获cut输出,且=前后无空格
SUNSET=$(cut -c 24-33 test.txt)
SUNRISE=$(cut -c 46-55 test.txt)
echo "Sunrise is expected at $SUNRISE and sunset at $SUNSET."

方法2:用jq解析JSON(推荐,稳定可靠)

jq是专门处理JSON的工具,能精准定位字段,不受JSON格式小变化影响。如果系统没有jq,可以通过包管理器安装(如apt install jq或brew install jq)。

#!/bin/bash
# 静默获取API响应(-s参数关闭curl进度输出)
RESPONSE=$(curl -s "https://api.sunrise-sunset.org/json?lat=48.813875&lng=2.392521")
# 用jq提取指定字段,-r参数输出原始字符串(不带引号)
SUNRISE=$(echo "$RESPONSE" | jq -r '.results.sunrise')
SUNSET=$(echo "$RESPONSE" | jq -r '.results.sunset')
# 格式化输出
echo "Sunrise is expected at $SUNRISE and sunset at $SUNSET."

更简洁的版本(无需保存整个响应):

#!/bin/bash
SUNRISE=$(curl -s "https://api.sunrise-sunset.org/json?lat=48.813875&lng=2.392521" | jq -r '.results.sunrise')
SUNSET=$(curl -s "https://api.sunrise-sunset.org/json?lat=48.813875&lng=2.392521" | jq -r '.results.sunset')
echo "Sunrise is expected at $SUNRISE and sunset at $SUNSET."

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:15:38