调用 CURL 时在 bash shell 脚本中的请求正文中反引号“`”

backtick " ` " in request body in bash shell script while calling CURL

我正在编写 CURL 命令

HTTP_Method : POST

API : api/databricks/query

Request body  {"query":" GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }

查询,我已经使用 POSTMAN 执行它正在工作

curl --location --request POST 'https://<databick_workspace-url>/api/sql/databricks/query' \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID` " }
# Working, And user can access DB

我认为问题出在反引号上,

// Function 
function grantReadAccess() {
  local path="/api/sql/databricks/query"
  local url="https://<databricks-workspace-url>/${path}"
  printf 'curl %q' "${url}"
  local DATABASENAME="DB-NAME"
  local userID="userID"

  local content="GRANT SELECT,READ_METADATA,USAGE on DATABASE \`${DATABASENAME}\` to \`${userID}\` "
  echo "------------$content" 
  // OUTPUT Here : GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID`
  // Same I have to pass in request body
  local permissionToGroup=$(
    curl -X POST "${url}" -H "Authorization: Bearer ${authtoken}" -H "Content-Type: application/json" -d '{ "query": \"'"${content}"'\" } ')
    //Required in this {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }

  echo "${permissionToGroup}"
}

// Tried In Postman insted of using backtick
 1. Single Quote "'" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE 'DB' to 'userID' "
 2. Blacket "(" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE (DB) to (userID) "

Error

{
  "query": "grant SELECT, READ_METADATA, USAGE on DATABASE 'DB' to 'useID' ",
    "data": null,
    "error": " org.apache.spark.sql.catalyst.parser.ParseException: \nOperation not allowed: grant(line 1, pos 0)\n\n== SQL ==\ngrant SELECT, READ_METADATA, USAGE on DATABASE 'DB"
}


以上功能无效,

你的问题不是很清楚,但我猜你在这部分遇到了问题:

-d '{ "query": \"'"${content}"'\" } '

这将使您在内容周围的双引号之前获得文字反斜杠,因为单引号内的反斜杠是按字面插入的。您可以将其换成 -d '{ "query": "'"${content}"'" }'-d "{ \"query\": \"${content}\" }"

当您需要构建 JSON 时,始终使用理解 JSON 的工具。在这种情况下,widely-accepted 工具的工作是 jq

curl -X POST "${url}" \
  -H "Authorization: Bearer ${authtoken}" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg content "$content" '{"query": $content}')"