Unary operators in Bash are operators that perform operations on a single operand, and they are often used for testing and evaluating conditions. For instance, the -n and -z operators are common examples, used for checking the length or emptiness of strings. Similar to this, several unary operators exist in the bash script. In this article, I am going to demonstrate different types of unary operators with examples. So let’s begin!
Free Downloads to Use the Unary Operators in Bash Scripts:
What is a Unary Operator in Linux?
A unary operator is an operator that works with only one operand, or in other words, it operates on a single value or variable. In programming languages like Bash, unary operators are used for tasks such as changing the sign of a number, incrementing or decrementing a value, negating a boolean value, checking the existence of a file, and more. For example:
- In the expression -x, the minus sign (-) is a unary operator that changes the variable’s sign.
- Another Expression is ++i, here the double plus sign (++) is a unary operator that increments the variable i by 1.
- In the expression !flag, the exclamation mark (!) is a unary operator that negates the boolean value of the variable flag.
Types of Unary Operators in Bash
In Bash scripting, several types of unary operators perform specific operations on a single operand. Here are the most commonly used types of unary operators based on their applications in Bash.
- Arithmetic Unary Operators (+ and -): The plus + and minus – operators are used to indicate the sign of numeric values. They are often used for making numbers positive or negative.
x=5 positive_x=+$x negative_x=-$x
- Logical Unary Operator ( ! NOT Operator): The exclamation mark ! is the logical NOT operator. It negates the result of a conditional expression, making it useful for inverting logical values.
value=true if ! $value; then echo "Value is false" else echo "Value is true" fi
- Bitwise Unary Operator (tilde ~ operator): The tilde ~ operator is used for bitwise NOT operations. It inverts the bits of a numeric value.
- String Value Checker Unary Operators (-z and -n): The -z operator checks if a string is empty, while the -n operator checks if a string is not empty.
str="Hello, World!" if [ -z "$str" ]; then echo "String is empty" else echo "String is not empty" fi
- File Test Unary Operators: Bash provides several unary operators to test file attributes, such as -e to check if a file exists, -f to verify if it’s a regular file, and -d to determine if it’s a directory.
file="example.txt" if [ -e "$file" ]; then echo "File exists" else echo "File does not exist" fi
- Variable Existence Unary Operator ( -v flag): The -v operator checks whether a variable exists or not. It is useful for ensuring a variable is defined before using it.
if [ -v var_name ]; then echo "Variable exists" else echo "Variable does not exist" fi
These unary operators are commonly used in conditional statements and tests to make decisions within Bash scripts.
6 Practical Examples of Using Unary Operators in Bash Script
Bash offers a range of unary operators crucial for conducting diverse tests and verifications within Bash scripts. These operators encompass -z for verifying empty strings, -n for non–empty strings, and ! for implementing logical NOT operations. Down below, you will have an overall demonstration related to this. Don’t forget to exercise those.
Example 01: Using Arithmetic Unary Operators to Calculate the Discount Price of a Product
Arithmetic unary operators in Bash are used for performing mathematical operations on numeric values. These operators include + and – for addition or subtraction. Let’s see a simple example given below.
- At first, launch an Ubuntu Terminal.
- Write the following command to open a file in Nano:
- Copy the script mentioned below:
#!/bin/bash # Define the original price of the product read -p "Enter the orginal price of the product: " original_price # Define the discount percentage read -p "Enter the discount price of the product: " discount_percentage # Calculate the discount amount discount_amount=$((original_price * discount_percentage / 100)) # Calculate the final discounted price discounted_price=$((original_price - discount_amount)) # Display the results echo "Original Price: $original_price dollars" echo "Discount Percentage: $discount_percentage%" echo "Discount Amount: $discount_amount dollars" echo "Discounted Price: $discounted_price dollars"
- 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 arithmetic.sh
- Run the script by the following command:
The image given above shows the result of a simple discount calculation where a product worth 200 dollars is reduced to 160 dollars discount price.
Example 02: Check the True Value Using Logical Unary Operator
Unlike the AND and OR operators, you can consider the NOT operator as a logical unary operator as the latter operator only works on a single operand. Here is a code demonstrated below for your perusal.
Script (logical.sh) >
#!/bin/bash # Prompt the user for a boolean input (true or false) read -p "Enter a boolean value (true or false): " user_input # Check if the user input is "true" using the logical NOT operator if ! [ "$user_input" == "true" ]; then echo "User input is NOT true." else echo "User input is true." fi
Use the following command to run the script in your command line
From the image given above, upon giving the true as a user value in the command line, the code states that “User input is true”.
Example 03: Using Bitwise Unary Operators to Calculate the Two’s Complement of Input Value
Bitwise unary operators in Bash are used to manipulate individual bits within integer values. These operators enable you to perform bitwise operations on numeric data. Here the objective of the code given below is to calculate the two’s complement of the input number by using the bitwise unary operator (~).
Script (bitwise.sh) >
#!/bin/bash # Prompt the user to enter an integer read -p "Enter an integer: " user_input # Check if the input is a valid integer if [[ $user_input =~ ^[0-9]+$ ]]; then num=$user_input # Use the bitwise unary operator ~ to invert the bits bitwise_not=$((~num)) # Display the results echo "Original number: $num" echo "Bitwise NOT of the number: $bitwise_not" else echo "Invalid input. Please enter a valid integer." fi
Run the script by using the following command
As the image shows above, the bash code converts the user input 10 into its complement of 2 and returns the output as -11 using the bitwise operator.
Example 04: Incorporating String Unary Operators to Check Whether the String is Empty or Not
Following the previous Example, here is another code I have developed using the string unary operator in the bash script. The objective of this code is to interact with the user and assess two input strings, providing feedback on whether each string is empty or not.
Script (string.sh) >
#!/bin/bash # Prompt the user to enter two strings read -p "Enter the first string: " first_input read -p "Enter the second string: " second_input # Check the first input using -z if [ -z "$first_input" ]; then echo "Using -z flag: The first input string is empty." else echo "Using -z flag: The first input string is not empty." fi # Check the second input using -n if [ -n "$second_input" ]; then echo "Using -n flag: The second input string is not empty." else echo "Using -n flag: The second input string is empty." fi
Write the following command in your terminal to execute the bash file
As the image suggests above, the bash code finds the first sting as a not empty string as integer 4 has been assigned to it. On the other hand, the second string is empty since no input data has been provided corresponding to it
Example 05: Using File Test Unary Operators to Check the File Properties
File test unary operators in Bash check the properties of files, directories, and related characteristics in shell scripts. They help you assess the conditions and properties of files, like existence, type, size, readability, writability, and more, enabling you to make decisions and take specific actions based on these properties in your scripts. Let’s see a sample code given below.
Script (file_test.sh) >
#!/bin/bash # Define the file path to be checked read -p "Enter your file name here: " file_path # Check if the file exists if [ -e "$file_path" ]; then echo "File '$file_path' exists." # Check if it's a regular file if [ -f "$file_path" ]; then echo "File '$file_path' is a regular file." # Check if it's readable if [ -r "$file_path" ]; then echo "File '$file_path' is readable." # Check if it's writable if [ -w "$file_path" ]; then echo "File '$file_path' is writable." else echo "File '$file_path' is not writable." fi else echo "File '$file_path' is not readable." fi else echo "File '$file_path' is not a regular file." fi else echo "File '$file_path' does not exist." fi
Now before running the bash script, let’s look at the list of files and directories using the ls command.
Here I want to check the file property for string.sh file. So to run the bash script, use the following command.
As you can see from the image given above, the string.sh is a file and has read, write, and execute permission. Upon execution of the bash file, the code validates all of those properties using the file test unary operator.
Example 06: Using Unary Operator to Check the Variable Existence
In Bash, though there is no specific variable existence unary operator. However, you can check the existence of a variable using unary operators, such as –v and -z, which can indirectly determine if a variable exists. For instance, the code provided below allows you to verify the presence and definition of a declared variable, both initially and after input, guiding you with informative messages throughout the process.
Script (variable_existence.sh) >
#!/bin/bash echo "No variable is set yet" # Check if a variable named 'my_variable' exists if [ -v my_variable ]; then echo "The variable 'my_variable' exists and is defined." else echo "The variable 'my_variable' does not exist or is not defined." fi # Define the variable 'my_variable' read -p "Enter the Variable Value: " my_variable # Check its existence again if [ -v my_variable ]; then echo "Now, the variable 'my_variable' exists and is defined." else echo "The variable 'my_variable' does not exist or is not defined." fi
Use the following command to run the script in the command line
As the image suggests above, the my_variable is not set yet, thus the code states that The variable ‘my_variable’ does not exist or is not defined. However, upon providing the variable value, the code states that my_variable exists and is defined.
In conclusion, Bash provides a set of unary operators that perform various tests and checks in Bash scripts. These operators include -z for checking empty strings, -n for non–empty strings, -a for logical AND, -o for logical OR, and ! for logical NOT. In this article, I have tried to demonstrate all of that information with some user examples. However, if you have any questions or queries related to this, feel free to comment below. Thank you!
People Also Ask
Is Unary a Type of Operator?
Yes, in computer programming and mathematics, a unary operator is a type of operator that operates on a single operand. Unary operators perform various operations on a single value, such as negating a number, incrementing or decrementing a value, or changing the sign. Common examples of unary operators include the negation operator (e.g., negating a number with a minus sign, like -5), the logical NOT operator (e.g., ! in Boolean operations), and the increment and decrement operators (e.g., ++ and — used to increase or decrease a value by 1).
What are the Three Most Used Unary Operators?
The three most frequently used unary operators in programming are the negation operator (–), the increment (++) and decrement (—) operators, and the logical NOT operator (!). The negation operator, represented by a minus sign (-), changes the sign of a numeric value, making, for example, -5 out of 5. The increment (++) and decrement (–) operators increase or decrease a variable’s value by 1. For instance, using x++ will increment the value of the variable x by 1, while y– will decrease the value of the variable y by 1. The logical NOT operator, expressed by an exclamation mark (!), is applied in Boolean operations to negate the truth value of an expression, effectively turning true into false and false into true.
Is Not Gate a Unary Operator?
Yes, the NOT gate, also known as a NOT operator, is indeed a unary operator. In digital logic and electronics, a NOT gate is a fundamental logic gate that performs a unary operation. It takes a single input and produces the opposite (complementary) output. When the input is true (1), the output is false (0), and vice versa. This operation is often represented using the symbol “¬” or “!” in Boolean algebra. It is a core component of logical operations and digital circuitry.
What does the >> operator do in Bash?
In Bash, the >> operator is used for output redirection. Specifically, it appends the output of a command or a piece of text to the end of a file, without overwriting the existing content of that file. It often adds new data to an existing file.
What does != Mean in a shell script?
In a shell script, != is an operator used for inequality comparison. It checks if two values or expressions are not equal. When you see != in a shell script, it means that the two items are not the same or do not have the same value.
What is $* in Linux?
In Linux operating systems, $* is a special shell variable. It represents all the command–line arguments (parameters) passed to a shell script as a single string. It treats all the arguments as a single entity, separated by spaces.
What is a Binary Operator in Bash?
In Bash, a binary operator is an operator that takes two arguments or operands to operate. Binary operators do a variety of tasks, including arithmetic calculations, comparisons, and logical operations.