Unary Operators in Bash

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

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!

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.

  1. 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
    
  2. 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
    
  3. Bitwise Unary Operator (tilde ~ operator): The tilde ~ operator is used for bitwise NOT operations. It inverts the bits of a numeric value.
    num=5
    bitwise_not=$((~num))
    
  4. 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
    
  5. 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
    
  6. 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 nonempty strings, and ! for implementing logical NOT operations. Down below, you will have an overall demonstration related to this. Don’t forget to exercise those.

1. 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.

To use how Unary Operators work in arithmetic operation, use 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"
EXPLANATION

The provided Bash script begins by prompting the user to enter the original price of the product, which is stored in the original_price variable, and the discount percentage, stored in the discount_percentage variable. It then calculates the discount amount by multiplying the original price by the discount percentage and dividing by 100, and this result is stored in the discount_amount variable.

Subsequently, the script calculates the final discounted price by subtracting the discount amount from the original price and stores it in the discounted_price variable. Finally, it displays the results, including the original price, discount percentage, discount amount, and the discounted price in dollars.

Using Arithmetic Unary Operators to Calculate the Discount Price of a ProductThe image given above shows the result of a simple discount calculation where a product worth 200 dollars is reduced to 160 dollars discount price.

2. 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.

To check the true value of user input, see the following bash script:

#!/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
EXPLANATION

First, user to enter a boolean value, which is expected to be either true or false, and stores the input in the user_input variable. Next, it uses the logical NOT operator (!) within an if-else statement to evaluate the user’s input. If the user’s input is not equal to true, the script executes the first block and informs the user that the input is not true. Conversely, if the user’s input matches true, the second block is executed, indicating that the user input is indeed true.

Check the True Value Using Logical Unary OperatorFrom the image given above, upon giving the true as a user value in the command line, the code states that “User input is true”.

3. 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 (~).

To calculate the two’s complement of a binary value using the unary operator, see the the script given below:

#!/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
EXPLANATION

This Bash script first prompts the user to enter an integer, which is stored in the user_input variable. It then checks if the input is a valid integer by using a regular expression pattern matching. If the input consists of one or more digits (^[0-9]+$), it proceeds with the calculations.

The script assigns the integer value to the num variable and then applies the bitwise unary operator () to invert the bits of the num using the $((~num)) expression. Finally, it displays the results, including the original number and the result of the bitwise NOT operation. If the user’s input is not a valid integer, it informs the user that the input is invalid and prompts them to enter a valid integer.

Using Bitwise Unary Operators to Calculate the Two's Complement of Input ValueAs 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.

4. 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.

To check whether a string is empty or not with unary operator, use the following command:

#!/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
EXPLANATION

This Bash script begins by requesting the user to input two strings, storing their responses in the first_input and second_input variables. The script employs two unary operators for string assessment:

  • -z: This operator checks if the first_input string is empty. If the first_input is an empty string, the script informs the user that it is indeed empty. However, if the first_input contains text, the script reports that the string is not empty, thus providing a clear evaluation of the input’s emptiness.
  • -n: The -n operator validates that the second_input string is not empty. If the second_input contains text, the script communicates that the string is not empty. Conversely, if second_input is empty, the script conveys that the string is indeed empty.

Incorporating String Unary Operators to Check Whether the String is Empty or NotAs 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

5. 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.

To check the file properties using unary operator, use the following bash code:

#!/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
EXPLANATION

The provided Bash script checks the status of a file specified by the user. It begins by prompting the user to enter a file path and stores it in the file_path variable. Then, it employs a series of nested if statements to assess the file’s characteristics.

First, it checks if the file exists using the -e option, and if it does, it informs the user. Next, it checks if the file is a regular file using the -f option and notifies the user accordingly. If the file is indeed a regular file, it proceeds to check if it’s readable with the -r option, and if it is, it reports that it’s readable.

Additionally, the script checks if the file is writable using the -w option, providing the user with information about the file’s writability. If at any point a condition is not met, such as the file not being readable or writable, the script informs the user accordingly. In case the file doesn’t exist at all, it reports that the specified file path does not exist.

Using File Test Unary Operators to Check the File PropertiesAs 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.

6. 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.

To check the variable existence with unary operator, use the following bash script:

#!/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
EXPLANATION

The provided Bash script begins by informing the user that no variable is set yet. It then checks for the existence and definition of a variable named my_variable using the -v option within an if-else statement. If my_variable exists and is defined, it prints a message confirming its existence; otherwise, it states that my_variable does not exist or is not defined.

Following this, the script prompts the user to enter a value for my_variable using the read command, and the user’s input is stored in the variable. The script then performs the same check for the existence and definition of my_variable again and provides messages as “The variable ‘my_variable’ does not exist or is not defined” by using the echo command.

 Using Unary Operator to Check the Variable ExistenceAs 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.

Conclusion

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 nonempty 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 commandline 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.

Related Articles


<< Go Back to Bash Operator | Bash Scripting Tutorial 

Rate this post
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