0

If I do:

if grep someexpression somefile >/dev/null; then
   ...
fi

Things work fine.

To do a "not", I know I can do this (using [] which is the test command):

if [ '!' somecondition ] ; then
   ...
fi

A simple workaround:

grep someexpression somefile >/dev/null
if [ '!' $? ]; then
   ...
fi

But the above workaround won't work with a while loop, so then I need to write a function instead, which is annoying. How do I do a not with the grep thing above, the proper way?

1 Answer 1

3

Try:

if ! grep someexpression somefile >/dev/null; then
   ...
fi

Note that the space after ! is mandatory, otherwise it will (try to) invoke history expansion.

Sign up to request clarification or add additional context in comments.

4 Comments

Interesting. Last time I had this problem, I tried exactly that, and it said something like "no such event". But your example worked fine.
tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html - it's even an example in the docs. (Works in ksh too, but I not sure if it is valid POSIX shell syntax.)
You had history expansion enabled. That shouldn't be a problem in a script. I disable it interactively because it causes more problems than it's worth. @Mat It's POSIX. It hasn't been around forever but I doubt there are serious users of such shells still around (way pre-bash/korn bourne shells).
@Peter: You probably did not put a space between the ! and grep. Without a space (on the command line), !grep will search your history for the last command starting with grep. With a space, it will work as a negation operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.