Reputation: 11028
I have 2 commands which I want to pipe like so: command1 | command2
. When command1
does not output anything at all command2
still outputs. How do I stop
command1 | command2
from outputting when command1
does not output anything?
Concrete example:
function find_string_in_file {
find . -iname "*$1*" | xargs ack-grep "$2"
}
alias findag='find_string_in_file'
If filename.py
does not exist in the current directory or its subfolders then findag filename.py "some word"
still returns the same output as ack-grep "some word"
.
Upvotes: 1
Views: 218
Reputation: 191749
You can change how you use xargs
to require ack-grep
to read arguments in line instead of through the pipe. This will work as you expect
find . -iname "*$1*" | xargs -I{} ack-grep "$2" {}
Upvotes: 1
Reputation: 531165
Pipes are not conditional, so you can't disable later stages based on the exit status of previous stages. For your particular example, you can modify the find
command to avoid the need for a pipeline.
find . -iname "*$1*" -exec ack-grep "$2" '{}' +
If there are no matching files, the exec
test won't be triggered.
Upvotes: 4