Table of Contents [hide]
In Bash, figuring out how you interpret the term if not condition before digging into the solutions is mandatory. For example, are you taking as negating the condition/expression, which means make the condition/expression False
if it is True
and vice versa? Or, you want to make some comparisons to assess inequality; this comparison can be of numbers or strings. We covered all the use cases below, and you can jump around to find your desired solution.
Comparing Numbers/Strings for Inequality
Use the -ne
operator to check if two numbers are not equal to each other in Bash.
Use !=
operator to check if strings are not equal to each other in Bash.
We can also assign string values to variables without wrapping them around with single or double quotes. See the following example.
Don’t add white space before and/or after the
=
sign while assigning value to the variables, such asstring1= 'Mehmood'
orstring1 = Mehmood
; otherwise, you will get an error illustrating the command not found.
Negating the Condition/Expression
Use the !
operator to negate the value of the specified condition meaning turn the resulting value to True
if it is False
and vice versa.
This example is similar to the one where we compared two numbers using the -ne
operator. In the above code, we negated the condition, which means the output of the [ $number1 -ne $number2 ]
condition was True
because 8
is not equal to 3
, but we turned this result into False
using !
operator; that’s why if
block was not executed but else
block.
Similarly, use the !
operator to negate the value of the specified condition for string values by turning the resulting value to True
if it is False
and vice versa.
For this code, the [ $string1 != $string2 ]
resulted in True
, but the !
operator made it False
, so the echo
command within the if
block was not executed and we didn’t get any output. So let’s practice the above example with an expression as follows.
Use the !
operator to negate the value of the specified expression for string values by turning the resulting value to True
if it is False
and vice versa.
Here, we used -z
to check if the specified string is empty, so the [ -z "$string"]
expression returned False
because $string
is not empty, but it was turned to True
due to using !
operator and resulted in if
block execution; otherwise, the else
block would be executed.