我有一个带有while循环的脚本,该脚本读取文件并收集一些值。循环停止后,可以再次操纵某些变量:
POWER=$(expect cisco_stats lab-asr9k-2 | awk '!/Total:/ || ++n <= 1' | egrep -v "show envi|CEST|RSP[0-1]")
while read -r line
do
if [[ $line == "Total:"* ]]
then t_use=$(echo "$line" | awk '{print $NF}')
continue
fi
if [[ $line == *"Type:"* ]]
then acdc=$(echo "$line" | awk '{print $NF}')
continue
fi
if [[ $line == "Total Power Capacity:"* ]]
then t_cap=$(echo "$line" | awk '{print $NF}')
continue
fi
if [[ $line == "Supply Protected Capacity"* ]]
then np1_av=$(echo "$line" | awk '{print $NF}')
npn_av="---"
break
fi
if [[ $line == "N+1 Supply Protected"* ]]
then np1_av=$(echo "$line" | awk '{print $NF}')
continue
fi
if [[ $line == "N+N Supply Protected"* ]]
then npn_av=$(echo "$line" | awk '{print $NF}')
break
fi
done <<< "$POWER"
if [[ $np1_av == *"Protected"* ]]
then np1_av="Not_Pr."
fi
if [[ $npn_av == *"Protected"* ]]
then npn_av="Not_Pr."
elif [ -z ${npn_av+x} ]
then npn_av="---"
fi
echo "$t_cap"
echo "$t_use"
echo "$acdc"
echo "$np1_av"
echo "$npn_av"
printf "%-10s %-10s %-10s %-10s %-10s\n" "Type" "Tot.cap." "In use" "N+1 prt." "N+N prt."
printf "%-10s %-10s %-10s %-10s %-10s\n" "$acdc" "$t_cap" "$t_use" "$np1_av" "$npn_av"
如果我分别回显每个变量-我会看到正确的结果。如果我尝试在一行中回显或打印变量,那么我只会看到在循环外部设置的变量:
4200W
1266.7
DC
Not_Pr.
---
Type Tot.cap. In use N+1 prt. N+N prt.
Not_Pr.
要删除文件的DOS行尾,可以使用它;
POWER=$(expect cisco_stats lab-asr9k-2 | awk '!/Total:/ || ++n <= 1' | egrep -v "show envi|CEST|RSP[0-1]" | sed 's/\r//' )
sed 's/\r//'
是删除文件中的回车
例如;
#!/bin/bash
# add carriage return variables
t_cap=$(echo '4200W' | sed 's/$/\r/')
t_use=$(echo 'DC' | sed 's/$/\r/')
acdc=$(echo 'Not_Pr.' | sed 's/$/\r/')
npn_av=$(echo '---' | sed 's/$/\r/')
np1_av=$(echo 'np1_av' | sed 's/$/\r/')
printf "%-10s %-10s %-10s %-10s %-10s\n" "Type" "Tot.cap." "In use" "N+1 prt." "N+N prt."
printf "%-10s %-10s %-10s %-10s %-10s\n" "$acdc" "$t_cap" "$t_use" "$np1_av" "$npn_av"
# remove carriage returns
t_cap=$(echo $t_cap | sed 's/\r//')
t_use=$(echo $t_use | sed 's/\r//')
acdc=$(echo $acdc | sed 's/\r//')
np1_av=$(echo $np1_av | sed 's/\r//')
npn_av=$(echo $npn_av | sed 's/\r//')
printf "%-10s %-10s %-10s %-10s %-10s\n" "Type" "Tot.cap." "In use" "N+1 prt." "N+N prt."
printf "%-10s %-10s %-10s %-10s %-10s\n" "$acdc" "$t_cap" "$t_use" "$np1_av" "$npn_av"
当运行这个 第二个printf的工作原理如下:
user@host:/tmp/test$ ./test.sh
Type Tot.cap. In use N+1 prt. N+N prt.
- np1_av
Type Tot.cap. In use N+1 prt. N+N prt.
Not_Pr. 4200W DC np1_av ---
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句