Return value of grep and ls

本文通过一系列测试案例,详细解析了Linux环境下ls和grep命令的返回值规律及其含义。当ls找不到指定文件时,返回值为2;若当前目录为空,则返回0。而grep根据是否匹配到行来决定其返回值,未找到匹配项时返回1,反之则返回0。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I make some testing below:

---------------------------------------------------------------------------------------------

$ ls

aa.txt  ab.txt  bb.txt

$ ls | grep -v 'aa.txt' | grep -v 'bb.txt'

ab.txt

$ echo $?

0

$ ls | grep -v 'aa.txt' | grep -v 'bb.txt' |grep -v 'ab.txt'

$ echo $?

1

$ ls | grep -E -v '(aa.txt|bb.txt|ab.txt)'

grep: illegal option -- E

Usage: grep -hblcnsviw pattern file . . .

$ ls | /usr/xpg4/bin/grep -E -v '(aa.txt|bb.txt|ab.txt)'

$ echo $?

1

$ ls abc.txt

abc.txt: No such file or directory

$ echo $?

2

--------------------------------------------------------------

From the testing above, we can find that if ls can’t find certain file,the return value will be 2,and display some error message, that is this command failed. If we use ls without parameters and there are no files in the current diretory, ls will return 0, that is this command successfully be executed.

But grep works in another way. According to the pattern grep will filter some lines. if no line get thought, the return value is 1, if some lines get thought, the return value is 0. so the return value of grep is 1 not mean grep fail, but no line get thought.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值