Bash - 我的脚本不记得变量

时间:2013-12-10 12:58:11

标签: bash variables ubuntu

我的脚本不起作用。它不记得变量的变化值。 我制作了以下剧本:

#!/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

为什么没有变化?

文件“list”如下:

         Debian_pokus   1
         debian_2       2
         debian_3       3

任何人,你能帮助我吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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