2015-02-09 97 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