Score:-1

How to fail command if zero or more than one line in output

id flag

Let's say I have a command like

git log --some-options

and I expect it to produce exactly one line so I could feed it to xargs, like git log --some-options | xargs git branch --all --contains

how do I make sure that, when git log command produces 0, or more than one, lines, then my command fails and git branch never gets called?

Score:3
us flag

Not running the command when there's no input to xargs is easy - it has the -r option for that. For most uses of xargs I've seen, you should be using this option.

Not running the command for more than one line of input can be trickier, but can be done by using, say, awk, to print the input only if there's one line:

... | awk 'END { if (NR == 1) print }'

For example:

% seq 1 10 | awk 'END { if (NR == 1) print }'
% # no output
% seq 1 | awk 'END { if (NR == 1) print }'
1

Then you can combine the two:

git log --some-options | awk 'END { if (NR == 1) print }' | xargs -r git branch --all --contains
Score:1
vn flag

Use wc -l like this:

[[ $(git log --some-options | wc -l) -eq 1 ]] && git log --some-options | xargs git branch --all --contains

The condition [[ $(git log --some-options | wc -l) -eq 1 ]] checks if the number of lines in the command git log --some-options is exactly 1, and if it's true runs the command after && (logical AND in bash).

id flag
I was thinking of this but it implies running the command twice, which I would rather avoid...
Artur Meinild avatar
vn flag
Yes, muru's solution is actually better in several ways! ^^
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.