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

Shell环境下从Curl输出提取access_token并存入变量的简便方法

最简实现方法(Shell 环境)

如果是在 Bash/Zsh 这类 shell 环境中,使用 jq 工具是最简洁可靠的方案,它专门用于处理 JSON 数据:

  • 直接将 API 调用结果通过管道传给 jq,提取 access_token 并赋值给变量:
# 替换成你的实际API调用命令
ACCESS_TOKEN=$(curl https://your-api-endpoint.com/token | jq -r '.access_token')

其中-r参数用于输出不带双引号的原始字符串,确保变量存储的是纯净的 token 值。

  • 如果 JSON 内容已保存到本地文件(比如 response.json),可以这样读取:
ACCESS_TOKEN=$(jq -r '.access_token' response.json)

补充说明

  • 若系统未安装 jq,可通过包管理器安装:Debian/Ubuntu 用 sudo apt install jq,CentOS/RHEL 用 sudo yum install jq,macOS 用 brew install jq。
  • 若不想额外安装工具,也可以用 awk 做字符串匹配(但这种方法对 JSON 格式变化容错性差,仅作参考):
ACCESS_TOKEN=$(curl https://your-api-endpoint.com/token | awk -F'"' '/access_token/ {print $4}')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:22:36