Shell脚本JSON参数转义异常排查及修正方案咨询
问题分析与解决方案
问题根源
- monitor.sh语法错误:
oauth_token"bar"缺少赋值符号=,应为oauth_token="bar",这会直接导致脚本执行失败。 - 参数传递的引号滥用:调用
checkAlive时手动给每个参数套额外引号(如'"POST"'),这些引号会被当成参数内容的一部分传递给api-check.sh。比如method变量会拿到"POST"(带双引号),而不是预期的POST;body会拿到'{"address":"Test address"}'(带单引号),导致curl发送的JSON格式错误。 - checkAlive函数的参数特性:函数内
"$@"已经会正确保留每个参数的边界,不需要在调用时手动加额外引号嵌套。
修复步骤
1. 修正monitor.sh的语法错误和参数调用
将monitor.sh中的错误代码修正:
api_url="foo" oauth_token="bar" # 修复缺失的赋值符号= body='{"address":"Test address"}' # 直接传递参数,无需手动添加额外引号 checkAlive "api-check.sh" "POST" "$api_url" "$oauth_token" "$body"
2. 验证参数传递正确性
修改后,checkAlive内执行echo "$@"会输出:
api-check.sh POST foo bar {"address":"Test address"}
此时api-check.sh能正确解析每个参数:
method="POST"url="https://foo"jwt="bar"body='{"address":"Test address"}'
3. 可选优化:api-check.sh的错误处理逻辑
原api-check.sh中curl的错误判断逻辑可以拆分,区分执行错误和HTTP状态码错误:
method="$1" url="https://$2" jwt="$3" body="$4" # 捕获curl执行阶段的错误(如网络不通、参数错误) if ! response_body=$(curl -s --request "$method" "$url" --header \ 'Authorization: Bearer '"$jwt" --header 'Content-Type: application/json' \ --header 'Accept: application/json' --data-raw "$body"); then echo "$url curl execution error" exit 2 fi # 单独获取HTTP状态码,判断业务层面的错误 http_code=$(curl -s -o /dev/null -w "%{http_code}" --request "$method" "$url" --header \ 'Authorization: Bearer '"$jwt" --header 'Content-Type: application/json' \ --header 'Accept: application/json' --data-raw "$body") if [ "$http_code" -ge 400 ]; then echo "$url returned HTTP code $http_code" exit 1 fi
修改后的完整脚本示例
修正后的monitor.sh
api_url="foo" oauth_token="bar" body='{"address":"Test address"}' checkAlive "api-check.sh" "POST" "$api_url" "$oauth_token" "$body"
无需修改的checkAlive函数
function checkAlive() { script="$1" args="${@:2}" startCheck=$(date +%s) echo "$@" tempResult="$( "$@" )" T_RC="$?" if [ "$T_RC" -ne 0 ]; then if [ "$result" = "" ]; then result="ERRORS: $tempResult" else result="$result ,, $tempResult" fi fi RC="$((RC > T_RC ? RC : T_RC))" timePassed }
内容的提问来源于stack exchange,提问作者CuriousGoat
相关产品推荐
相关产品推荐

