如何在输出管道的第一个命令时不输出任何内容

时间:2013-02-23 19:42:00

标签: linux bash shell pipe

我有2个命令,我想管道如下:command1 | command2。当command1在所有command2仍然输出时不输出任何内容时。我该怎么办? 当command1 | command2没有输出任何内容时输出command1

具体例子:

function find_string_in_file {
find . -iname "*$1*" | xargs ack-grep "$2"
}
alias findag='find_string_in_file'

如果当前目录或其子文件夹中不存在filename.py,则findag filename.py "some word"仍会返回与ack-grep "some word"相同的输出。

2 个答案:

答案 0 :(得分:4)

管道不是有条件的,因此您无法根据前一阶段的退出状态禁用后续阶段。对于您的特定示例,您可以修改find命令以避免需要管道。

find . -iname "*$1*" -exec ack-grep "$2" '{}' +

如果没有匹配的文件,则不会触发exec测试。

答案 1 :(得分:1)

您可以更改使用xargs要求ack-grep在行中而不是通过管道读取参数的方式。这将按预期工作

find . -iname "*$1*" | xargs -I{} ack-grep "$2" {}
相关问题