如何在curl的--data-binary参数中使用变量?附Python替代方案
问题解决:curl --data-binary 变量引用及Python替代方案
Shell脚本修复方案
你的问题出在给$file_at添加了多余的引号,curl识别@文件名格式时不需要额外包裹引号。直接构造变量即可,以下是两种正确写法:
写法一:单独定义文件引用变量
# 构造带日期的文件名 file=~/myname-"$(date +"%Y-%m-%d")".abc # 直接拼接@前缀,无需额外引号 file_at="@$file" # 执行curl命令,变量需加双引号避免特殊字符拆分 curl -H "Content-Type: application/timestamp-query" --data-binary "$file_at" https://someserver.com --output myname-"$(date +"%Y-%m-%d")".def
写法二:直接在curl中使用变量
file=~/myname-"$(date +"%Y-%m-%d")".abc curl -H "Content-Type: application/timestamp-query" --data-binary "@$file" https://someserver.com --output myname-"$(date +"%Y-%m-%d")".def
关键注意事项:
- 变量引用必须加双引号
"@$file",防止文件名含空格或特殊字符时被Shell错误拆分 - 不要给
@文件名额外添加引号,curl需要直接识别@前缀来读取文件内容
Python替代方案(requests版本)
import requests from datetime import datetime # 生成日期字符串并构造文件名 date_str = datetime.now().strftime("%Y-%m-%d") input_file_path = f"~/myname-{date_str}.abc" output_file_path = f"~/myname-{date_str}.def" # 读取待上传的文件内容 with open(input_file_path, "rb") as f: file_content = f.read() # 发送POST请求 headers = {"Content-Type": "application/timestamp-query"} response = requests.post("https://someserver.com", headers=headers, data=file_content) # 将响应内容写入输出文件 with open(output_file_path, "wb") as f: f.write(response.content)
Python替代方案(httpx版本)
import httpx from datetime import datetime # 生成日期字符串并构造文件名 date_str = datetime.now().strftime("%Y-%m-%d") input_file_path = f"~/myname-{date_str}.abc" output_file_path = f"~/myname-{date_str}.def" # 读取待上传的文件内容 with open(input_file_path, "rb") as f: file_content = f.read() # 发送POST请求 headers = {"Content-Type": "application/timestamp-query"} with httpx.Client() as client: response = client.post("https://someserver.com", headers=headers, data=file_content) # 将响应内容写入输出文件 with open(output_file_path, "wb") as f: f.write(response.content)
内容的提问来源于stack exchange,提问作者user3819370
相关产品推荐
相关产品推荐

