Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Negate an if Condition in a Bash Script in Linux
To negate an if condition in a Bash script in Linux, you can use the ! operator (logical NOT). This operator reverses the truth value of a condition ? if the condition would normally be true, negation makes it false, and vice versa. For example, instead of checking if [ $x -eq 5 ], you can use if [ ! $x -eq 5 ] to execute commands when the variable is not equal to 5.
Basic Negation Syntax
The ! operator is placed inside the test brackets, immediately after the opening bracket:
if [ ! condition ]
then
# Commands to execute when condition is false
fi
Integer Comparison with Negation
Bash provides several operators for comparing integers:
-eq(equal to)-ne(not equal to)-gt(greater than)-ge(greater than or equal to)-lt(less than)-le(less than or equal to)
Examples with Negation
# Check if x is NOT equal to 5
if [ ! $x -eq 5 ]
then
echo "x is not equal to 5"
fi
# Check if x is NOT greater than 10
if [ ! $x -gt 10 ]
then
echo "x is less than or equal to 10"
fi
String Comparison with Negation
For string comparisons, Bash offers these operators:
=(equal to)!=(not equal to)-z(string is empty)-n(string is not empty)
Examples with String Negation
# Check if string is NOT equal to "hello"
if [ ! "$s" = "hello" ]
then
echo "s is not equal to hello"
fi
# Check if string is NOT empty
if [ ! -z "$s" ]
then
echo "s is not an empty string"
fi
Alternative Approaches
Instead of using negation, you can often use the opposite comparison operator:
| Negated Condition | Equivalent Direct Condition |
|---|---|
[ ! $x -eq 5 ] |
[ $x -ne 5 ] |
[ ! "$s" = "hello" ] |
[ "$s" != "hello" ] |
[ ! -z "$s" ] |
[ -n "$s" ] |
Using Double Brackets
Bash also supports [[ ]] (double brackets) for more advanced conditional expressions:
# Using double brackets with negation
if [[ ! "$x" -eq 5 ]]
then
echo "x is not equal to 5"
fi
# Pattern matching with negation
if [[ ! "$filename" == *.txt ]]
then
echo "File is not a text file"
fi
Key Points
Always include spaces around brackets and operators:
[ ! condition ]Enclose string variables in double quotes:
"$variable"The
!operator works with any test condition or commandDouble brackets
[[ ]]provide more flexibility than single brackets[ ]
Conclusion
Negation in Bash using the ! operator allows you to reverse any conditional test, making your scripts more flexible and readable. Whether comparing integers, strings, or testing file conditions, negation provides a powerful way to handle alternative logic flows in your shell scripts.
