如何在Shell脚本中提取Git API返回JSON数组首元素的browser_download_url?
To grab the browser_download_url from the first release (which is the latest release, since GitHub returns releases in reverse chronological order) returned by the GitHub API, the most robust and straightforward tool to use is jq—a lightweight command-line JSON processor.
Here's the complete command you can use in your shell script:
curl -s https://api.github.com/repos/$owner/$repo/releases | jq -r '.[0].assets[] | select(.browser_download_url != null) | .browser_download_url'
Breakdown of the command:
curl -s: Runs curl in silent mode, suppressing progress bars and extra output so only the raw JSON response is passed to the next command.jq -r: The-rflag tells jq to output raw strings without surrounding quotes, making the URL ready for direct use (like in awgetorcurldownload command)..[0]: Targets the first element in the JSON array of releases (the newest one, as GitHub sorts releases from newest to oldest)..assets[]: Iterates over all assets attached to that release.select(.browser_download_url != null): Filters out any assets that don't have a download URL (some releases might only include source code archives without pre-built binaries)..browser_download_url: Extracts and prints the actual download URL for each matching asset.
Simplified version (if you know there's only one asset):
If you're certain the first release has exactly one asset you care about, you can shorten the command to:
curl -s https://api.github.com/repos/$owner/$repo/releases | jq -r '.[0].assets[0].browser_download_url'
Installing jq (if you don't have it):
Most Linux distros and macOS have jq available via package managers:
- Debian/Ubuntu:
sudo apt update && sudo apt install jq - macOS (with Homebrew):
brew install jq - RHEL/CentOS/Fedora:
sudo dnf install jq
While it's technically possible to parse JSON with tools like sed or awk, those methods are fragile—they can break if the JSON structure changes (like extra whitespace or reordered keys). jq is designed specifically for this use case and is far more reliable.
内容的提问来源于stack exchange,提问作者Bhranee

