- 论坛徽章:
- 0
|
我现在在自学SHELL,看教程的时候有个问题搞不懂,教材上有以下代码和说明(该程序目的大概就是接受一个人名,然后在某一个文档中查找所有匹配该名字的条目,然后将查找到的条目依次显示出来并询问是否删除该条目,如果选“Y”那么就删除):
#
# Remove someone from the phone book
#
name=$1
#
# Get matching entries and save in temp file
#
grep "$name" $PHONEBOOK > /tmp/matches$$
if [ ! -s /tmp/matches$$ ]
then
echo "I can't find $name in the phone book"
exit 1
fi
#
# Display matching entries one at a time and confirm removal
#
while read line
do
display "$line" #display 是另外一个程序,这行的意思就是显示变量"$line"的内容
echo "Remove this entry (y/n)? \c"
read answer < /dev/tty
if [ "$answer" = y ]
then
break
fi
done < /tmp/matches$$
rm /tmp/matches$$
if [ "$answer" = y ]
then
if grep -v "^$line$" $PHONEBOOK > /tmp/phonebook$$
then
mv /tmp/phonebook$$ $PHONEBOOK
echo "Selected entry has been removed"
else
echo "Entry not removed"
fi
fi
教材的解释:
The rem program collects all matching entries into a temporary file. If the size of the file is zero, no match was found and an appropriate message is issued. Otherwise, for each matching entry, the program displays the entry and asks the user whether that entry is to be removed. This provides reassurance to the user that the entry the user intends to remove is the same one that the program intends to remove, even in the single match case.
After a y has been typed to the program, a break command is executed to exit from the loop. Outside the loop, the program tests the value of answer to determine how the loop was exited. If its value is not equal to y, then the user doesn't want to remove an entry after all (for whatever reason). Otherwise, the program proceeds with the removal by greping out all lines but the desired one (and here the pattern specified to grep is made to match only entire lines by anchoring it to the start and end of the line).
我不明白,既然在while循环中有个判断语句
if [ "$answer" = y ]
then
break
fi
那么程序执行到这里,如果"$answer" = y ,将会跳出while循环,执行后面的程序代码,那么怎么可能实现:“for each matching entry, the program displays the entry and asks the user whether that entry is to be removed.”加入有grep命令找到3个匹配的,然后显示了第一个,问是否删除,选"Y",不就跳出循环继续下面的代码了吗?那么后面的2个匹配的跟本就没被处理啊,因为已经跳出循环了啊(我的问题就是这里想不通,请高手指点迷津)
[ 本帖最后由 lkwsxdz 于 2008-5-8 09:05 编辑 ] |
|