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

如何在Bash中为curl传递多个动态请求头?

问题:Bash中curl无法正确处理request_header数组参数

在Bash脚本中使用数组传递curl请求头时,无法达到预期效果,但硬编码-H参数却能正常运行。测试代码如下:

#!/bin/bash

send_example_by_array() {
    local -a request_header=()
    
    request_header[0]="-H"
    request_header[1]="\"Accept: */*\""
    
    request_header[2]="-H"
    request_header[3]="\"Accept-Language: en-US,en;q=0.5\""
    
    curl "${request_header[@]}" --verbose --silent --location "https://www.example.com"
}

send_example_by_array

send_example_by_hard_code_headers_in_command_line_one_by_one() {
    curl -H "Accept: */*" -H "Accept-Language: en-US,en;q=0.5" --verbose --silent --location "https://www.example.com"
}

send_example_by_hard_code_headers_in_command_line_one_by_one

使用数组传递参数时,curl的verbose输出显示重复的请求头,且无法返回页面内容:

> Host: www.example.com
> user-agent: curl/7.81.0
> accept: */*
> "accept: */*"
> "accept-language: en-US,en;q=0.5"
> 
* TLSv1.2 (IN), TLS header, Supplemental data (23):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.2 (IN), TLS header, Supplemental data (23):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
* TLSv1.2 (IN), TLS header, Supplemental data (23):
* TLSv1.2 (OUT), TLS header, Supplemental data (23):
* TLSv1.2 (IN), TLS header, Supplemental data (23):
* TLSv1.2 (IN), TLS header, Supplemental data (23):
* TLSv1.2 (IN), TLS header, Supplemental data (23):
* HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1)
* stopped the pause stream!
* Connection #0 to host www.example.com left intact

而硬编码参数时,请求头正常,能返回页面内容:

> GET / HTTP/2
> Host: www.example.com
> user-agent: curl/7.81.0
> accept: */*
> accept-language: en-US,en;q=0.5
> 
...
< content-length: 1256
< 
* TLSv1.2 (IN), TLS header, Supplemental data (23):
* TLSv1.2 (IN), TLS header, Supplemental data (23):
<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
...
</body>
</html>

问题原因

数组元素中添加了多余的转义双引号。在硬编码时,双引号是Shell用来识别参数边界的语法,不会传递给curl;但数组中写入的\"Accept: */*\"会被当成参数的一部分,导致curl把带双引号的字符串作为请求头的值发送。同时,curl本身会默认发送Accept: */*头,最终出现重复请求头,服务器解析异常引发协议错误。

修复方案

去掉数组元素里的转义双引号,直接将-H和对应的请求头内容作为独立的数组元素:

#!/bin/bash

send_example_by_array() {
    local -a request_header=()
    
    # 直接添加参数,无需转义引号
    request_header+=("-H" "Accept: */*")
    request_header+=("-H" "Accept-Language: en-US,en;q=0.5")
    
    curl "${request_header[@]}" --verbose --silent --location "https://www.example.com"
}

send_example_by_array

修改后,数组展开时会将每个-H和对应的请求头正确分割为独立参数,和硬编码的效果完全一致,curl能正常发送请求并获取页面内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:28:23