2016-10-06 49 views
1

我有一個帶while循環的腳本,它讀取一個文件並收集一些值。循環停止後,一些變量可以再次被操縱:echo和printf不打印分配在bash循環中的變量

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" 

如果我分別回顯每個變量 - 我看到正確的結果。如果我嘗試回聲或在一行printf的變量,我只看到哪裏設置循環之外的變量:

4200W 
1266.7 
DC 
Not_Pr. 
--- 
Type  Tot.cap. In use  N+1 prt. N+N prt. 
    Not_Pr. 

+0

您的腳本中或您正在讀取的命令的輸出中有DOS行結束符。 – chepner

+0

你是說這是問題嗎?我怎樣才能改變這個? –

+0

http://stackoverflow.com/tags/bash/info – chepner

回答

1

刪除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的作用如下:

[email protected]:/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  --- 
+0

謝謝。我在設置POWER變量時刪除了DOS行結尾,並且它正常工作。非常感謝。 ( –