shell 遍历文件时 尽量用重定向而不用管道

场景:遍历文件,找到某行含关键字即退出

#!/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.  内建命令和外部命令的区别在于前者不需要使用子进程来执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值