场景:遍历文件,找到某行含关键字即退出
#!/bin/bash
file="data.txt"
function func1
{
while [ 1 ]
do
sleep 2
cat $file | while read line
do
if [[ $line == *"second"* ]]
then
echo "func1 -> line with second : $line"
return 10
fi
done
done
}
function func2
{
while [ 1 ]
do
sleep 2
while read line
do
if [[ $line == *"second"* ]]
then
echo "func2 -> line with second : $line"
return 10
fi
done < $file
done
}
func1
echo "return: $?"
调用 func1,输出:
func1 -> line with second : this is the second line
func1 -> line with second : this is the second line
func1 -> line with second : this is the second line^C
即无限循环,不会退出
调用 func2 ,输出:
func2 -> line with second : this is the second line
return: 10
解释:to do ...
1. 进程列表、协程和管道(第11 章会讲到)都利用了子shell;
2. 内建命令和外部命令的区别在于前者不需要使用子进程来执行