# SuSE 发行版中提取的脚本片段:
# --------------------------------------------------------------#
while read des what mask iface; do
# 一些命令 ...
done < <(route -n)
# ^ ^ 第一个 < 是重定向,第二个是进程替换。
# 为了测试,我们让它来做点儿事情。
while read des what mask iface; do
echo $des $what $mask $iface
done < <(route -n)
# 输出内容:
# Kernel IP routing table
# Destination Gateway Genmask Flags Metric Ref Use Iface
# 127.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 lo
# --------------------------------------------------------------#
# 正如 Stéphane Chazelas 指出的,
#+ 一个更容易理解的等价代码如下:
route -n |
while read des what mask iface; do # 通过管道输出设置的变量
echo $des $what $mask $iface
done # 这段代码的结果更上面的相同。
# 但是,Ulrich Gayer 指出 . . .
#+ 这段简化版等价代码在 while 循环里用了子 shell,
#+ 因此当管道终止时变量都消失了。
# --------------------------------------------------------------#
# 然而,Filip Moritz 说上面的两个例子有一个微妙的区别,
#+ 见下面的代码
(
route -n | while read x; do ((y++)); done
echo $y # $y is still unset
while read x; do ((y++)); done < <(route -n)
echo $y # $y has the number of lines of output of route -n
)
# 更通俗地说(译者注:原文本行少了注释符)
(
: | x=x
# 似乎启动了子 shell ,就像
: | ( x=x )
# 而
x=x < <(:)
# 并没有。
)
# 这个方法在解析 csv 和类似格式时很有用。
# 也就是在效果上,原始 SuSE 系统的代码片段就是做这个用的。