Usages of “NOT (!)” Operator in Bash Scripting [4 Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

The “! (NOT) operator in Bash scripting is a logical operator used to invert the exit status of a command. It’s valuable for conditionals and error checking. In this article, I will demonstrate 3 different examples of using the NOT operator in bash scripting. So let’s start.

NOT Operator in Shell Script

In shell scripting, the NOT operator is represented by the exclamation mark (!). It is used to negate a condition or logical expression. When you place the NOT operator before a condition, it flips the condition’s truth value. For example, ! true becomes false, and ! false becomes true. The  NOT operator is commonly used in conditional statements to reverse the logic and perform actions when a condition is not met. It’s a fundamental tool for making decisions and creating complex logic in shell scripts.

Syntax of the NOT Operator in Bash Script

In Bash, the basic syntax of NOT Operator is as follows:

if [ ! condition ]; then
  # Code to execute if the condition is not true
fi

Or,

if [[ ! condition ]]; then
  # Code to execute if the condition is not true
fi

Or,

if ! test condition; then
     command1
     command2
fi

In each syntax, the exclamatory sign (!) flips the output value of the conditions such that it returns true if the condition gives false and false if the conditional exit status is true.

4 Practical Examples of Using the NOT Operator in Bash Scripts

Given below, there are 4 practical examples that I have articulated for your perusal. The example will articulate the effective way of string and integer comparison. Further, you will learn how to check whether a variable is empty or not using the NOT operator. Lastly, you will learn the way to negate the IF conditional. Don’t forget to run those codes in your command line.

1. Using NOT Operator for String Comparison in Bash

In my first code, the objective is to allow a user to input two strings and then compare them to determine whether they are equal or not. Check and follow the steps given below and replicate the same in your terminal.

To use the NOT operator for string comparison, use the script mentioned below:

#!/bin/bash

#taking the input value from the user
read -p "Enter the first string: " str1
read -p "Enter the second string: " str2

#checking whether the given strings are equal or not
if [ "$str1" != "$str2" ]; then
  echo "Strings are not equal."
else
  echo "Strings are equal."
fi
EXPLANATION

The provided Bash script facilitates a user-driven comparison of two inputted strings. It begins by prompting the user to enter the first string, storing this input in the variable str1. Subsequently, it instructs the user to input the second string, saving it in str2.

Then the script employs the != operator within an if statement to evaluate whether str1 is dissimilar to str2. If the condition proves true, indicating inequality between the two strings, the script outputs “Strings are not equal.” Conversely, if the condition is false, signifying that the strings are identical, it outputs “Strings are equal.”

Using NOT Operator for String Comparison in BashUpon giving Hello and World strings to the command line, the bash script declares “Strings are not equal” to the command line. However, when I put LinuxSimply twice as the variable value, the code returns “Strings are equal”, indicating the string match based on the provided string.

2. Inserting NOT Operator for Integer Comparison in Bash

Following the previous code, I want to enable users to input two numerical values and compare them to determine if they are equal or not. To accomplish the task, I will use the NOT operator in a bash script.

To compare integer numbers using the NOT operator, follow the script below:

#!/bin/bash

read -p "Enter the first number: " number1
read -p "Enter the second number: " number2

if [ ! "$number1" -eq "$number2" ]; then
  echo "Numbers are not equal."
else
  echo "Numbers are equal."
fi
EXPLANATION

The given bash code prompts users to enter the values, stores them in variables, and then employs the -eq operator within an if statement. If the numbers are not equal, as indicated by the ! operator before the condition, the script outputs “Numbers are not equal.” Conversely, if the numbers are equal, it displays “Numbers are equal” by using the echo command.

Inserting NOT Operator for Integer Comparison in BashAs you can understand from the image given above, the code can successfully identify the equality of two given integers and return the corresponding response to the command line.

3. Checking the Variable Whether Empty Using NOT Operator in Bash

In this code, the objective is to allow a user to define a variable and then determine whether the provided variable is empty or not. To do so, I will incorporate a NOT operator to accomplish the task.

To check if a variable is empty or not using the NOT operator, use the script given below:

#!/bin/bash

read -p "Enter a value: " userVar

if [ ! -z "$userVar" ]; then
  echo "The variable is not empty."
else
  echo "The variable is empty."
fi
EXPLANATION

This Bash script is designed to assess whether a user-inputted variable, denoted as userVar, is empty or not. It begins by using the read command along with a prompt to collect user input, which is stored in userVar. Subsequently, it employs an if statement to evaluate the condition [ ! -z “$userVar” ], wherein the not operator ! is used in combination with the -z flag to check if userVar is not empty. If the condition holds true, the script prints “The variable is not empty.” Conversely, if the condition is false, indicating that the variable is empty, it outputs “The variable is empty.”

Checking the Variable Whether Empty Using NOT Operator in BashAs the image depicts above, the bash code gives a prompt to the user and asks to enter a value. In the first case, I did not put a null value to the assigned variable and subsequently, the code returns “The variable is empty” to the command line. However in the second case, Upon giving the “Random Value” as a string to the variable, the script says “The variable is not empty”.

4. Negate the IF condition in a Bash Script Using the ! (NOT) Operator

From the script given below, you will learn how to negate if condition using the ! NOT operator in a bash script with two different approaches. One is incorporating! sign inside the double square bracket and the other is keeping the sign outside of the double square bracket.

When the NOT operator resides outside the double square brackets [[, it will run the expression(s) enclosed within the brackets and invert the outcome. That means, If you have multiple expressions, then the entire result will be negated. On the other hand, If you put NOT Operator inside the double square, then the operator will be applied only to the individual expression.

To negate a IF condition using a NOT operator, use the following script:

#!/bin/bash

# Assign a value to the 'num' variable
read -p "Give me the first number to be evaluated: " num1

# Check if 'num1' is not equal to 0
if ! [[ $num1 -eq 0 ]]
then
  # If the condition is true, print a message
  echo "Value of first number is not 0"
fi

read -p "Insert the second number: " num2 

# Check if 'num2' is not equal to 0
if [[ ! $num2 -eq 0 ]]
then
  # If the condition is true, print a message
  echo "Value of the second number is not 0 either"
fi
EXPLANATION

The given bash code utilizes the ! (NOT) operator outside of the -eq (equal) operator and double square brackets [[ … ]]. Subsequently, the user has a prompt to enter the first number, storing it in the num1 variable, and checking if num1 is not equal to 0. If this condition is met, the script prints the message “Value of the first number is not 0.”

In the second part of the code, it uses the ! operator with the -eq operator also within double square brackets and is applied when the user is prompted to input the second number, which is stored in the num2 variable. The script then checks if num2 is not equal to 0 using this method, and if the condition holds true, it displays the message “Value of the second number is not 0 either”.

Negate the IF condition in a Bash Script Using the ! (NOT) OperatorAs you can see from the image above, both methods return the same output successfully.

Conclusion

In Bash scripting, the NOT operator effectively reverses the truth value of a condition or expression. By placing the NOT operator before a statement, one can transform true into false and false into true. In this article, I have demonstrated an overview of the NOT operator in bash. However, if you have any questions or queries related to this article, feel free to comment below. Thank you.

People Also Ask

What does != Mean in shell script?

In a shell script, “!=” means “not equal to.” It’s used in conditional statements to compare two values and check if they are not the same.

What is an example of a not operator?

In shell scripting, the NOT operator, represented as “!“, is used to negate a condition. For instance, “if ! -f file.txt” checks if “file.txt” does not exist, enabling you to take specific actions when a particular condition is not met, and adding flexibility to your scripts.

Is the NOT operator a binary operator?

The NOT operator (!) is a unary operator in shell scripting, acting on a single operand to negate its logical value. It reverses true to false and false to true, making it a fundamental tool for creating conditional statements and handling logical expressions in scripts.

What is the not in binary code?

In binary code, the not operation is represented as a bitwise NOT operator, usually denoted as “~.” It flips each bit, turning 0 into 1 and 1 into 0.


Related Articles


<< Go Back to Bash Logical Operators | Bash Operator | Bash Scripting Tutorial

5/5 - (3 votes)
Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment