我正在尝试使用另一个变量的值创建一个变量名。 首先,我正在编写的其他可以起作用的代码示例:
#!/bin/bash
j=0
let "AVG_T_${j}"+="(${TEMPS[$j]})" #Works
let "tLen"="(${#AVG_T_0[@]})" #Works
tLen=${#AVG_T_0[@]} #Works
let "AVG_T_0=${AVG_T_0[@]:1}" #Works
let "AVG_T_${j}"="${AVG_T_0[@]:1}" #Works
这是我遇到的麻烦:
#!/bin/bash
j=0
"tLen"="(${#AVG_T_${j}[@]})" #Bad Substitution
let "AVG_T_${j}"="${AVG_T_${j}[@]:1}" #Bad Substitution
我不知道使它起作用的方法。我尝试了许多不同的语法,方括号,无等。 我不知道从那里去哪里。
谢谢
这是我现在的位置。该代码应该检查温度区域的温度,然后给出电流输出和平均输出。
j=0
TEMPS=()
AVGtn=5
DIRECTORY="/sys/class/thermal/thermal_zone"${j}
while [ -d "$DIRECTORY" ];
do
eval "AVG_T_${j}_TOTAL="""
TEMPS+=($(cat $DIRECTORY/temp))
TEMPS[$j]=$(convert ${TEMPS[$j]})
eval "AVG_T_${j}+=(\"\${TEMPS[${j}]}\")"
eval "tLen=\${#AVG_T_${j}[@]}" #Works
if [ $tLen -gt $AVGtn ]; then
eval "AVG_T_${j}=(\"\${AVG_T_${j}[@]:1}\")"
eval "tLen=\${#AVG_T_${j}[@]}"
AVG_T=()
eval "AVG_T+=(\"\${AVG_T_${j}[@]}\")"
for i in ${AVG_T[@]}; do
let "AVG_T_${j}_TOTAL"+=${i}
done
eval "x=\${AVG_T_${j}_TOTAL}"
let "AVG_TMP_${j}=(1000*($x/$tLen)+5)/1000"
fi
let "j++"
DIRECTORY="/sys/class/thermal/thermal_zone"${j}
sleep 3
done
这就是我最终得到的结果。我知道它可能会被收紧和清理,但是我很高兴拥有有效的代码。也许它将帮助像我这样的其他外行继续前进。
j=0
TEMPS=()
DIRECTORY="/sys/class/thermal/thermal_zone"${j}
while [ -d "$DIRECTORY" ];
do
# Put TOTAL to null
eval "AVG_T_${j}_TOTAL="""
# Add one directory temp to TEMPS
TEMPS+=($(cat $DIRECTORY/temp))
# Convert TEMP to Celsius
TEMPS[$j]=$(convert ${TEMPS[$j]})
# Put the converted TEMP into AVG_T_n
eval "AVG_T_${j}+=(\"\${TEMPS[${j}]}\")"
# Get the current Length of AVG_T_n
eval "tLen=\${#AVG_T_${j}[@]}"
# If the len of AVG_T_n is greater than AVGtn
if [ $tLen -gt $AVGtn ]; then
# Take Oldest temp out of Array
eval "AVG_T_${j}=(\"\${AVG_T_${j}[@]:1}\")"
# Reset tLen Length to the new length
eval "tLen=\${#AVG_T_${j}[@]}"
fi
# Clear AVG_T
AVG_T=()
# Get an AVG_T_${j} duplicate duplicate from eval named AVG_T so we can use it as a condition that the for loop understands
eval "AVG_T+=(\"\${AVG_T_${j}[@]}\")"
# Add all of AVG_T values together and put into AVG_T_n_TOTAL
for i in ${AVG_T[@]}; do
let "AVG_T_${j}_TOTAL"+=${i}
done
# Ceate a variable with eval so that we can use it in the formula that provides the average temperature
eval "x=\${AVG_T_${j}_TOTAL}"
# Create the AVG_TMP_n
eval let "AVG_TMP_${j}=\"(1000*(\$x/\$tLen)+5)/1000\""
# Convert the AVG_TMP_n to Fahrenheit
eval let "AVG_TMP_${j}f=\"\$(convertc2f AVG_TMP_${j})\""
# Create another variable for echo for testing
let "j++"
DIRECTORY="/sys/class/thermal/thermal_zone"${j}
done
答案 0 :(得分:0)
我们可以使用eval
。
#!/bin/bash
set -exu
declare -a AVG_T_0=(first second third fourth)
j=0
eval "tLen=\${#AVG_T_${j}[@]}"
eval "AVG_T_${j}=(\"\${AVG_T_${j}[@]:1}\")"
typeset -p tLen
typeset -p AVG_T_0
typeset -p "AVG_T_${j}"