Shell函数接收请求方法参数后异常:curl解析错误与重复输出
mycurl Function Is Failing Alright, let's break down exactly what's causing the curl: (6) Could not resolve host: GET error and the duplicate 30 count:
The Core Issue: Duplicate $@ Usage
Your modified mycurl function uses "$@" twice in the curl command, which completely messes up argument parsing.
When you call mycurl GET https://api.layer.com/apps/9d649224-cde5-11e7-b916-f3d1a15f96fe/exports, the "$@" variable expands to the full list of arguments you passed: GET https://api.layer.com/....
This turns your curl command into:
curl -X GET https://api.layer.com/... \ -H 'Accept: application/vnd.layer+json; version=3.0' \ -H 'Authorization: Bearer qFyBLjM9mhOlIwjZCeblbV9CrLZh2rqNzVIlIuf8a07UBj5F' \ -H 'Content-Type: application/json' \ GET https://api.layer.com/...
1. The "Could not resolve host: GET" Error
Curl follows the syntax curl [options] URL.... After processing the first valid URL (https://api.layer.com/...), it treats the remaining GET as a second URL to request. Since GET isn't a valid hostname (there's no DNS record for it), curl throws the "Could not resolve host" error.
2. The Duplicate 30 Count
Notice that after the GET "URL" fails, curl still processes the final https://api.layer.com/... argument as a third URL. That means you're actually sending two valid GET requests to the API: once from the first URL, once from the last.
Both requests return the same data, so when you parse the combined output with jq -r '.|length', you get two separate 30 values. The echo $count command then prints both numbers together.
How to Fix It
You need to separate the request method from the rest of the arguments. Here's the corrected mycurl function:
mycurl() { # Capture the first argument as the HTTP method local http_method="$1" # Remove the first argument from the list, leaving only the URL/extra options shift curl -X "$http_method" \ -H 'Accept: application/vnd.layer+json; version=3.0' \ -H 'Authorization: Bearer qFyBLjM9mhOlIwjZCeblbV9CrLZh2rqNzVIlIuf8a07UBj5F' \ -H 'Content-Type: application/json' \ "$@" }
local http_method="$1"grabs the first argument (your HTTP method likeGETorPOST).shiftremoves that first argument from the argument list, so"$@"now only contains the URL and any extra curl options you might pass later.- Now curl will only send one request to the correct URL, eliminating both the error and duplicate counts.
内容的提问来源于stack exchange,提问作者frigocat

