为什么我的变量没有重置为零?

为什么我的变量没有重置为零?

在下面的循环中,我尝试将两个变量(totalentries 和totalusedbytes)的值重置为零,但从结果中我可以看到它从未发生。因此,每个循环继续添加到前一个循环的运行总数中

# For each grid name, get a list of map indexes for that gridname
for grid in "${gridNames[@]}"
   do
      totalentries=0
      totalusedbytes=0
      indexlist=`snmpwalk -v 2c -c splunk $host mapGridName -m $APPLIANCEMIB -OUQs -Ln | grep $grid | sed -n 's/.*mapGridName\.\([0-9]\+\)[^0-9].*/\1/p'`
      # Split list into an array
      while read -r line; do
          indexes+=(`echo $line`)
      done <<< "$indexlist"

      # Get the stats
      for index in "${indexes[@]}"
      do
         # Entries in Cache
         numentries=`snmpget -v 2c -c splunk $host mapNumEntries.$index -m $APPLIANCEMIB -OUQs -Ln | sed -n 's/.*\=[^0-9]\([0-9]\+\).*/\1/p'`
         # Used Bytes
         usedbytes=`snmpget -v 2c -c splunk $host mapUsedBytes.$index -m $APPLIANCEMIB -OUQs -Ln | sed -n 's/.*\=[^0-9]\([0-9]\+\).*/\1/p'`
         if [[ $numentries ]]
         then
             totalentries=`expr $totalentries + $numentries`
         fi
         if [[ $usedbytes ]]
         then
             totalusedbytes=`expr $totalusedbytes + $usedbytes`
         fi
      done
      echo $grid"_totalentries="$totalentries
      echo $grid"_totalusedbytes="$totalusedbytes
   done

这是输出,循环中的大多数网格什么都没有,但它们得到了前一个循环的总和

A_grid_totalentries=0
A_grid_totalusedbytes=0
B_grid_totalentries=3
B_grid_totalusedbytes=30142
C_totalentries=3
C_totalusedbytes=30142
D_grid_totalentries=3
D_grid_totalusedbytes=30142
E_grid_totalentries=3
E_grid_totalusedbytes=30142
F_totalentries=3
F_totalusedbytes=30142
G_grid_totalentries=92
G_grid_totalusedbytes=1054348
H_grid_totalentries=96
H_grid_totalusedbytes=1114431
I_grid_totalentries=96
I_grid_totalusedbytes=1114431

答案1

问题是您不断添加到索引数组,并且从不重置它。当您将这些变量重置为零时,将数组设置为空:

  totalentries=0
  totalusedbytes=0
  indexes=()

或者,以不同的方式填充数组:

  mapfile -t indexes <<< "$indexlist"

相关内容