繁体   English   中英

将文件内容回显到 curl 命令中

[英]echo contents of file into a curl command

我正在尝试运行 curl 命令,如下所示:

curl -X POST "https://$CLUSTER/api/internal/vmware/vm/snapshot/$snapshot_id/restore_files" -H "accept: application/json" -H "authorization: "$authType" "$hash_password"" -H "Content-Type: application/json" -d "{\"destObjectId\": \"$vm_id\", \"restoreConfig\": [ echo $(cat suhas_file.txt) ], \"shouldUseAgent\": true, \"shouldRestoreXAttrs\": true}" -k -s

我收到Request Malformed

由于echo $(cat suhas_file.txt)

如果我手动运行这个 echo 命令,我会得到:

echo $(cat suhas_file.txt)
{\"path\": \"C:\\\\bootmgr\"},{\"path\": \"C:\\\\Program Files\\\\desktop.ini\"}

如果我在上面的 curl 中手动粘贴而不是 echo

curl -X POST "https://$CLUSTER/api/internal/vmware/vm/snapshot/$snapshot_id/restore_files" -H "accept: application/json" -H "authorization: "$authType" "$hash_password"" -H "Content-Type: application/json" -d "{\"destObjectId\": \"$vm_id\", \"restoreConfig\": [ {\"path\": \"C:\\\\bootmgr\"},{\"path\": \"C:\\\\Program Files\\\\desktop.ini\"} ], \"shouldUseAgent\": true, \"shouldRestoreXAttrs\": true}" -k -s

有用。

我试过了

value=`cat suhas_file.txt`

然后在 curl 中echo $value ,我仍然收到格式错误的请求。

我怎样才能在 curl 的[]中基本上回显我们在上面看到的这个文件的内容

尝试:

printf -v data '
    {
        "destObjectId": "%s",
        "restoreConfig": [%s],
        "shouldUseAgent": true,
        "shouldRestoreXAttrs": true
    }
' "$vm_id" "$(< suhas_file.txt)"

curl -X POST \
    -H "accept: application/json" \
    -H "authorization: $authType $hash_password"" \
    -H "Content-Type: application/json" \
    -d "$data" \
    -k -s \
    "https://$CLUSTER/api/internal/vmware/vm/snapshot/$snapshot_id/restore_files"

为可读性添加了续行。

suhas_file.txt文件中,不要转义双引号——它应该是普通的 JSON 数据。

$(< filename)是一个 bash 结构,相当于$(cat filename) 参见手册中的3.5.4 命令替换

为了从 shell 脚本安全地组合动态 JSON 数据集,像jq这样的 JSON 感知解析器将确保正确格式化。

例子:

#!/usr/bin/env sh

authType='authTypeBasic'
hash_password='samplePassword'
snapshot_id='snapshot42'
vm_id='Marvin'

data="$(
  jq \
    --null-input \
    --compact-output \
    --arg VMID "$vm_id" \
    --rawfile restoreConfig suhas_file.txt \
    '{
      "destObjectId": $VMID,
      "restoreConfig": [ $restoreConfig | split("\n") ],
      "shouldUseAgent": true,
      "shouldRestoreXAttrs": true
    }'
  )"
curl \
  --request 'POST' \
  --header "Accept: application/json" \
  --header "Authorization: $authType $hash_password" \
  --header "Content-Type: application/json" \
  --data "$data" \
  --insecure \
  --silent \
  --url "https://$CLUSTER/api/internal/vmware/vm/snapshot/$snapshot_id/restore_files"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM