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:

foo=1
bar=2

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

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:

foo=Hello
bar=World

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

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:

num=1
if ! [[ $num -eq 0 ]]
then
  echo "Value of num is not 0"
fi

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:

num=1
if [[ ! $num -eq 0 ]]
then
  echo "Value of num is not 0"
fi

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.