2017-08-16 99 views
1

嘿,我正在使用管道捲曲方法從帖子創建任務。當我使用硬編碼值從終端運行時,它工作正常。但是,當我嘗試用變量來執行它,它拋出一個錯誤:使用bash腳本解析curl中的變量

腳本:

#!/bin/bash 
echo "$1" 
echo "$2" 
echo "$3" 
echo "$4" 
echo "$5" 
echo '{ 
    "transactions": [ 
    { 
     "type": "title", 
     "value": "$1" 
    }, 
    { 
     "type": "description", 
     "value": "$2" 
    }, 
    { 
     "type": "status", 
     "value": "$3" 
    }, 
    { 
     "type": "priority", 
     "value": "$4" 
    }, 
    { 
     "type": "owner", 
     "value": "$5" 
    } 
    ] 
}' | arc call-conduit --conduit-uri https://mydomain.phacility.com/ --conduit-token mytoken maniphest.edit 

執行:

./test.sh "test003 ticket from api post" "for testing" "open" "high" "ahsan" 

輸出:

test003 ticket from api post 
for testing 
open 
high 
ahsan 
{"error":"ERR-CONDUIT-CORE","errorMessage":"ERR-CONDUIT-CORE: Validation errors:\n - User \"$5\" is not a valid user.\n - Task priority \"$4\" is not a valid task priority. Use a priority keyword to choose a task priority: unbreak, very, high, kinda, triage, normal, low, wish.","response":null} 

正如你所看到的錯誤讀取$ 4和$ 5作爲值不變量。而且我無法理解如何在這些參數中使用$變量作爲輸入。

回答

1

您使用的是最後一個echo附近的單引號,以便您可以在JSON中使用雙引號,但這會導致echo在不擴展任何內容的情況下打印字符串。您需要爲該字符串使用雙引號,因此您必須將其中的雙引號轉義。

將最後echo本:

echo "{ 
    \"transactions\": [ 
    { 
     \"type\": \"title\", 
     \"value\": \"$1\" 
    }, 
    { 
     \"type\": \"description\", 
     \"value\": \"$2\" 
    }, 
    { 
     \"type\": \"status\", 
     \"value\": \"$3\" 
    }, 
    { 
     \"type\": \"priority\", 
     \"value\": \"$4\" 
    }, 
    { 
     \"type\": \"owner\", 
     \"value\": \"$5\" 
    } 
    ] 
}" 

,它會工作。要避免這樣的問題,您可以檢查http://wiki.bash-hackers.orghttp://mywiki.wooledge.org/BashGuide,以獲得bash新手的一些常規提示。此外,你可以使用shellcheck與許多文本編輯器,這會自動發現這樣的錯誤。