1

In a project, I have a test setup where I read the exit status $? of a command.

In my test, I want to ensure that the string foobar is not present in the output.

When I run the command:

./program | grep foobar

It returns 1, indicating a failure.

I need it to return 0.

Is there a way to negate the return value?

1 Answer 1

3

! inverts the exit code of a pipeline.

! ./program | grep -q foobar
3
  • 1
    This inverts all non-zero exit codes into 0 and 0 to 1. But what most want in this scenario is to only invert 0 <-> 1. Using ! doesn't just change the result of exit code 1 (grep for not found) but also other codes like 2. A important thing to note about this answer is that it uses grep -q which changes the exit-code behavior to not exit with non-zero exit code even on fatal errors. Commented Sep 3, 2024 at 8:08
  • @CervEd Your opinion what most people might want in this situation should be a comment on the question, not on an answer. Why do you put all this in a comment anyway instead of providing an additional answer...? Commented Sep 3, 2024 at 20:18
  • I'm providing additional context which I believe is important to understand why this works for this particular problem formulation and invocation of grep (grep -q) but not grep without the quiet flag or other commands which use exit code 1 for something that is not an error and other exit codes for errors (like diff) Commented Sep 4, 2024 at 8:04

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.