2015-02-09 100 views
0

因此,我正在製作一個腳本,允許您輸入一個數字,將其導出,然後將其導入並在循環中使用它。這是我的意思:ASH使變量名稱變爲兩個變量

read NumberOfVMs "How many do you want? " 
echo $NumberOfVMs > /variables/NumberOfVMs 

然後;

while [ $NumberOfVMs -gt 0 ];do 
    # This is the loop I use to repeat the effects I want. 
    # This method works fine for me. 
    NumberOfVMs=$((NumberOfVMs-1)) 
done 

然而,是什麼讓我的是,我需要使用由數列出的變量(基於什麼$ NumberOfVMs是公平的。我也想填零到四和0的號碼。我知道我可以零墊做$(printf %04g $NumberOfVMs)

例如,我希望能夠提出3個變量(分別與0001,0002和0003添加到變量名的末尾)在提問時我正在做像這樣

while [ $NumberOfVMs -gt 0 ];do   
    read -p "Enter percentage of RAM to allot GuestOS (1-99): " percentram$(printf %04g $NumberOfVMs) 
    NumberOfVMs=$((NumberOfVMs-1)) 
done 

而且,雖然我確實相信e(我可能是錯的),說percentram0001正在編寫 - 我無法弄清楚如何在使用變量時如何動態使用它,因爲 $percentram$(printf %04g $NumberOfVMs)不等於percentram0001,而是等於percentram的輸出並添加0001。

請,如果你能幫助我,我會永遠愛你。

+2

你使用bash。你有陣列。使用數組。 – 2015-02-09 04:54:09

+0

http://stackoverflow.com/questions/16553089/bash-dynamic-variable-names - 此鏈接有相同的信息。 – 2015-02-09 05:39:37

+0

我實際上使用灰,只是標記爲bash,因爲它更常見 – Crutchcorn 2015-02-10 05:02:00

回答

2

您可以使用eval黑客:

NumberOfVMs=10 
read -p "Enter percentage of RAM to allot GuestOS (1-99): " count 
eval "percent$(printf %04g $NumberOfVMs)=$count" 
echo $percent0010 
+0

:D非常感謝您的回覆!我會完全檢查出來,看看發生了什麼 – Crutchcorn 2015-02-10 04:58:51

+0

這工作! ILY !!!! – Crutchcorn 2015-02-10 05:13:30

+0

等等....但是,那麼我怎樣才能讀取它作爲動態?我現在知道如何設置$ percent0010,但是如何根據有多少虛擬機來讀取$ percent $(printf%04g $ NumberOfVMs)(本例中爲percent0010)? – Crutchcorn 2015-02-10 05:15:35