你可以使用這裏-DOC:
foo=$(cat <<EOF
{"Comment":"Update DNSName.","Changes":[{"Action":"UPSERT","ResourceRecordSet":{"Name":"alex.","Type":"A","AliasTarget":{"HostedZoneId":"######","DNSName":"$bar","EvaluateTargetHealth":false}}}]}
EOF
)
通過在第一線未加引號離開EOF
,在這裏,文檔的內容將受到參數擴展,所以你$bar
擴展到任何你放在那裏。
如果你可以在你的JSON換行符,你可以把它多一點可讀性:
foo=$(cat <<EOF
{
"Comment": "Update DNSName.",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "alex.",
"Type": "A",
"AliasTarget": {
"HostedZoneId": "######",
"DNSName": "$bar",
"EvaluateTargetHealth": false
}
}
}
]
}
EOF
)
甚至(每行頭縮進必須是一個選項卡)
foo=$(cat <<-EOF
{
"Comment": "Update DNSName.",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "alex.",
"Type": "A",
"AliasTarget": {
"HostedZoneId": "######",
"DNSName": "baz",
"EvaluateTargetHealth": false
}
}
}
]
}
EOF
)
和以顯示如何存儲,包括引用(假設bar=baz
):
$ declare -p foo
declare -- foo="{
\"Comment\": \"Update DNSName.\",
\"Changes\": [
{
\"Action\": \"UPSERT\",
\"ResourceRecordSet\": {
\"Name\": \"alex.\",
\"Type\": \"A\",
\"AliasTarget\": {
\"HostedZoneId\": \"######\",
\"DNSName\": \"baz\",
\"EvaluateTargetHealth\": false
}
}
}
]
}"
因爲t他的擴張shell元字符,你可能會遇到麻煩,如果你的JSON包含有類似*
,所以或者,你可以直接分配,但要小心引述周圍$bar
:
foo='{"Comment":"Update DNSName.","Changes":[{"Action":"UPSERT","ResourceRecordSet":{"Name":"alex.","Type":"A","AliasTarget":{"HostedZoneId":"######","DNSName":"'"$bar"'","EvaluateTargetHealth":false}}}]}'
通告$bar
的引用:這是
"'"$bar"'"
^^^ ^^^
||| |||
||| ||literal double quote
||| |opening syntactical single quote
||| closing syntactical double quote
||opening syntactical double quote
|closing syntactical single quote
literal double quote
這工作完美,特別是感謝酒吧的報價細目,解決了未來的問題! – Alex