Bash脚本中反引号执行curl时参数$4未被解析的问题
Bash脚本中curl请求grant_type参数传递失败的解决方法
问题场景
在Bash脚本中执行以下curl命令获取token:
CURL_RESPONSE=`curl --request POST "$1" --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'grant_type="$4"' --data-urlencode 'scope=operator test' --data-urlencode 'client_id=$2' --data-urlencode 'client_secret=$3' -s
运行后返回错误:
curl Response is {"code":"400","description":"Invalid grant_type. Only client_testcred is accepted"}
已确认client_testcred已传入$4参数,尝试数组传参方式也无效:
args=(--request POST "$1" --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'grant_type=client_credentials' --data-urlencode 'scope=operator supervisor' --data-urlencode 'client_id=$2' --data-urlencode 'client_secret=$3' -s) CURL_RESPONSE=`curl "${args[@]}`
问题原因
核心问题是单引号包裹的变量不会被Bash解析:
- 原命令中
'grant_type="$4"'、'client_id=$2'里的$4、$2被单引号保护,curl实际发送的是字符串"$4"和$2,而非传入的真实参数值 - 数组写法中不仅存在单引号导致变量未解析的问题,还遗漏了
${args[@]}的闭合符号}
解决方法
方法1:修正直接执行的curl命令
将包含变量的参数改用双引号,确保Bash解析变量后再传递给curl:
CURL_RESPONSE=$(curl --request POST "$1" \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode "grant_type=$4" \ --data-urlencode 'scope=operator test' \ --data-urlencode "client_id=$2" \ --data-urlencode "client_secret=$3" -s)
固定字符串(如scope)可继续使用单引号,无需解析的内容不受影响。
方法2:修正数组传参的写法
确保变量所在参数用双引号解析,同时补全数组语法的闭合符号:
args=( --request POST "$1" --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode "grant_type=$4" --data-urlencode 'scope=operator supervisor' --data-urlencode "client_id=$2" --data-urlencode "client_secret=$3" -s ) CURL_RESPONSE=$(curl "${args[@]}")
数组参数分行书写更易维护,变量部分用双引号保证解析正确。
验证要点
执行脚本时需保证参数顺序正确,调用格式示例:
./your-script.sh https://auth-server-url/token your-client-id your-client-secret client_testcred
内容的提问来源于stack exchange,提问作者Spiderweb Computer Technologie
相关产品推荐
相关产品推荐

