Usages of NOT (!) Operator in Bash Scripting [4 Examples]
Usages of NOT (!) Operator in Bash Scripting, the logical operator “!“ (NOT) is used to flip a command’s exit state. It is useful error checking and conditions. I’ll go over three distinct uses of the NOT operator in bash scripting in this article. Now let’s get going.
Key Takeaways
- Understanding the role of the NOT operator in bash script.
- Checking the existence of the variable value using the NOT operator in a bash script.
NOT Operator in Shell Script
Usages of NOT (!) Operator 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
The exclamation mark (!) in each syntax flips the conditions’ output value, returning false in the case that the condition returns false and true in the case that the conditional exit status is true.
4 Practical Examples of Using the NOT Operator in Bash Scripts
Here are four real-world instances that I have explained for your review. The example will demonstrate how to compare strings and integers effectively. Additionally, you will discover how to use the NOT operator to determine if a variable is empty or not. Finally, you will discover how to eliminate the IF conditional. Remember to execute those scripts from your command line.
Example 01: Using NOT Operator for String Comparison in Bash
The aim of my initial code is to enable the user to enter two strings and thereafter perform a comparison to ascertain their equality. Verify, adhere to the instructions provided below, and repeat the process in your terminal.
- At first, launch an Ubuntu Terminal.
- Write the following command to open a file in Nano:
nano string_comparison.sh
EXPLANATION- nano: Opens a file in the Nano text editor.
- string_comparison.sh: Name of the file.
- Copy 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
EXPLANATIONTwo inputted strings can be compared by the user with the help of the supplied Bash script. It starts by asking the user to enter the first string, which is then saved in the str1 variable. It then gives the user instructions to enter the second string and stores it in str2.
- Press CTRL+O and ENTER to save the file; CTRL+X to exit.
- Use the following command to make the file executable:
chmod u+x string_comparison.sh
EXPLANATION
- chmod: Changes the permissions of files and directories.
- u+x: Here, u refers to the “user” or the owner of the file and +x specifies the permission being added, in this case, the “execute” permission. When u+x is added to the file permissions, it grants the user (owner) permission to execute (run) the file.
- string_comparison.sh: File name.
- Run the script by the following command:
./string_comparison.sh
Upon 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.
Example 02: Inserting NOT Operator for Integer Comparison in Bash
I want to allow users to enter two numerical numbers and compare them to see if they are equal or not, using the previous code as a guide. I’ll use a bash script with the NOT operator to complete the operation. Adhere to the script provided here.
To save and make the script executable, simply follow the instructions in Example 01.
Script (integer_comparison.sh) >
#!/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
The provided bash code uses an if statement with the -eq operator after asking users to submit values and storing them in variables. The script outputs “Numbers are not equal” if the numbers are not equal, as indicated by the! operator preceding the condition. On the other hand, the echo command is used to display “Numbers are equal” if the numbers are equal.
Use the following command to run the code
./integer_comparison.sh
As 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.
Example 03: Checking the Variable Whether Empty Using NOT Operator in Bash
The goal of the code in my previous example is to let the user enter a value and then assess if it is empty or not. Like previously, I’ll use a NOT operator to complete the operation.
To save and make the script executable, simply follow the instructions in Example 01.
Script (variable_check.sh) >
#!/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
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.”
Run the code by using the following command
./variable_check.sh
The accompanying graphic illustrates how the bash code prompts the user to enter a value. In the first instance, the code returns “The variable is empty” to the command line since I neglected to set the assigned variable to a null value. But in the second scenario, the script states that “The variable is not empty” after the user enters a text representing the “Random Value” into the variable.
Example 04: Negate the IF condition in a Bash Script Using the ! (NOT) Operator
You will learn how to negate an if condition in a bash script using two different methods by examining the script provided below, which uses the! NOT operator. The difference between the two is that one places the! sign inside the double square bracket while the other leaves it outside.
The expression(s) enclosed in the brackets will be run and the result will be inverted when the NOT operator is located outside the double square brackets [[. This implies that if you use more than one expression, the outcome will be canceled out. However, the operator will only be applied to the specific phrase if you place the NOT Operator inside the double square.
You can follow the steps of Example 01, to save & make the script executable.
Script (negate_if.sh) >
#!/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
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.”
The second section of the code is used when the user is prompted to enter the second number, which is kept in the num2 variable, and it makes use of the! operator with the -eq operator likewise inside double square brackets. Next, using this method, the script determines whether or not number2 is not equal to 0. If the criteria is met, it shows the message “Value of the second number is not 0 either.”
Run the code by using the following command
./negate_if.sh
As you can see from the image above, both methods return the same output successfully.
Conclusion
The NOT operator in Bash scripting effectively flips an expression or condition’s truth value. The NOT operator can be used to convert true statements into false statements and false statements into true statements. I’ve covered the basics of the Bash NOT operator in this article. However, please feel free to leave a comment below if you have any questions or concerns about this article. I’m grateful.