簡體   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