這個問題在這里已經有了答案: Bash 中的動態變數名稱 18 個答案 17 小時前關閉。
我有這些變數:
var1=ab
var2=cd
result=${var1}-text-${var2}
ab-text-cd=bingo
我有:
$ echo $result
ab-text-cd
我想擁有:
$ echo $result
bingo
有可能嗎?怎么做?
更多資訊:Var1 和 var2 是給腳本的引數。
uj5u.com熱心網友回復:
感謝@Léa Gris。我不知道“間接引數擴展”。
"If the first character of PARAMETER is an exclamation point, Bash uses the value of the variable formed from the rest of PARAMETER as the name of the variable."
解決方案 :
result2=$(echo ${!result1})
uj5u.com熱心網友回復:
您可以使用eval來實作這一點。但請注意,使用eval幾乎總是一個壞主意,因為它存在明顯的安全問題(植根于其設計 - 它旨在執行傳遞給它的所有內容),除此之外,各種事情都可能出錯變數具有意外值。
result=${var1}-text-${var2}
eval ${var1}'_text_'${var2}=bingo
echo $ab_text_cd
此外,環境變數不能將破折號 (-) 作為變數名的一部分,因此在示例中我將它們替換為下劃線 (_)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/420656.html
標籤:
