我的脚本不起作用。它不记得变量的变化值。 我制作了以下剧本:
#!/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
任何人,你能帮助我吗?
答案 0 :(得分:2)
有FAQ on this exact question on Greycat wiki(bash参考)。
bash
所以请使用adequate test:[[ … ]]
或(( … ))
; cat
,grep
can't take a file as input(例如:grep <pattern> <file>
)。while …; do …; done < <(cmd)
详细了解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