1. Introduction

In bash programming, one of the most common controlling construct is the if statement. It lets us choose from different courses of action by comparing variables.

In this tutorial, we’re going to learn how to negate such conditions in bash, concentrating on the number and string comparison.

2. Integer Comparison

Let’s say we have two variables that hold numbers. In bash, we can check for their inequality using the -ne comparison operator:


if [[ $foo -ne $bar ]]
  echo "The integers are not equal"

This example will print the result “The integers are not equal”:

The integers are not equal

3. String Comparison

Likewise, we can compare strings. Note that foo and bar are holding strings now, instead of numbers:


if [[ $foo != $bar ]] 
  echo "The strings are not equal" 

After execution, we’ll see the following output:

The strings are not equal

It is important to note that != should be used for string, whereas -ne is used for numbers.

4. Negation

We can negate the if condition using the ! (not) operator:

if ! [[ expr ]]; then

When we use the not operator outside the [[, then it will execute the expression(s) inside [[ and negate the result.

Let’s see an example to understand it better:

if ! [[ $num -eq 0 ]]
  echo "Value of num is not 0"

If the value of num equals 0, the expression returns true. But it’s negated since we have used the not operator outside the double square brackets. If we have multiple expressions, then the entire result is negated.

We can also use the not operator for individual expressions inside [[ :

if [[ ! expr ]]; then

Let’s consider another example:

if [[ ! $num -eq 0 ]]
  echo "Value of num is not 0"

Here we have used the not (!) operator for an individual expression. When we have multiple expressions, the not (!) operator is applied only to the individual expression.

Generally, it’s common to use the ! operator inside the double square brackets.

5. Conclusion

In this short article, we’ve seen different ways to negate the if condition in bash.

First, we learned the different operators used for numeric and string comparisons in bash. Then, we saw how to use the not (!) operator to negate the conditions. Finally, we looked at the difference between using the not operator inside and outside the double square brackets.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.