2013-12-10 46 views
2

我的腳本不起作用。它不記得變量的變化值。 我做了下面的腳本:Bash - 我的腳本不記得變量

#!/bin/bash 

kon_p=100 
kon_m="nothing" 

cat /etc/list | grep -v '#' | while read machine priority ; 
do 
    if [ $priority -le $kon_p ] 
    then 
     kon_p=$priority 
     kon_m=$machine 

    fi 

done 

echo priority machine is $kon_m with priority $kon_p 

,其結果是:

priority machine is nothing with priority 100 

爲什麼沒有變化?

文件 「列表」 是繼

  Debian_pokus 1 
     debian_2  2 
     debian_3  3 

任何你能幫助我嗎?

+4

的變量是在由'while'打開子shell設置,所以主要的進程沒有訪問他們。 – fedorqui

+3

請參閱http://mywiki.wooledge.org/BashFAQ/024以獲取詳盡的解釋,包括解決方法。 –

+0

您應該得到一個獎勵:http://partmaps.org/era/unix/award.html – cdarke

回答

2

有一個FAQ on this exact question on Greycat wiki(bash參考)。

什麼是錯

瞭解更多關於process substitution

解決方案

#!/bin/bash 

kon_p=100 
kon_m="nothing" 

while read machine priority ; do 
    if (($priority < $kon_p)); then 
     kon_p=$priority 
     kon_m=$machine 
    fi 
done < <(grep -v '#' /etc/list) 

printf "priority machine is %s with priority %s\n" "$kon_m" $kon_p 
+0

非常感謝,它的工作 – Joffo

+0

考慮驗證它,如果這是正確的解決方案。 –

0

子shell是在做你的,這應該工作:

#!/bin/bash 

kon_p=100 
kon_m="nothing" 

IFS=$'\n' 
for line in $(cat /etc/list | grep -v '#') 
do 
    IFS=' ' read -ra values <<< "${line}" 
    if [ ${values[1]} -le $kon_p ] 
    then 
     echo "doing it." 
     kon_p=${values[1]} 
     kon_m=${values[0]} 
    fi 
done 

echo priority machine is $kon_m with priority $kon_p 
+2

不要做循環['for ... in $()'](http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Conditional_Loops_.28while.2C_until_and_for.29),它的行爲*不一致*取決於來源。還請閱讀[分詞](http://mywiki.wooledge.org/WordSplitting) –

+0

請給我一個鏈接來閱讀它。 – cforbish

+0

加入我的評論 –