Imagine you’re responsible for managing a complex server infrastructure, you need to automate routine tasks, validate user inputs, and make decisions based on various conditions. This is where the Bash operator comes into play. In our comprehensive overview, I’ll explore the world of Bash operators, providing some relevant examples within the discussion. So let’s start!
What is a Bash Operator?
In Bash scripting, an operator is a special symbol or keyword used to perform specific operations on data or variables. These operators enable you to manipulate and control data within your Bash scripts. Just like in mathematics, where operators like addition and subtraction perform mathematical operations on numbers, Bash operators perform operations on data within your scripts. Broadly, The bash operator can be segmented into six types. These are:
- Arithmetic operators
- Logical operators
- Relational Operators
- Bitwise operators
- File test operators
- Unary operators.
When to Use the Various Bash Operators?
Bash operators are fundamental for controlling script flow and data manipulation. The list that I am going to provide below is an overview of when you will use which types of bash operators to accomplish different tasks.
- Arithmetic Operators: Use arithmetic operators like + and – when you need to perform mathematical operations in your Bash scripts, such as addition or subtraction.
- Comparison Operators: Utilize comparison operators (-eq, -ne) when you want to evaluate conditions, typically in if statements or loops, to make decisions based on comparisons between values.
- Logical Operators: Employ logical operators (&&, ||) when you need to create complex conditions by combining multiple conditions.
- String Operators: Apply string operators (=, !=) when working with text data to compare or manipulate strings, making it useful for tasks like pattern matching or string manipulation.
- Assignment Operators: Use assignment operators (=, +=) to manage variable values by assigning new values to variables or appending values to existing ones.
- File Operators: Utilize file operators (-e, -f) when you need to check file properties, such as whether a file exists (-e) or whether it is a regular file (-f).
- Bitwise Operators: Employ bitwise operators (&, |) to manipulate individual bits within numbers, which is useful in scenarios like low-level data manipulation or flag setting.
- Ternary Operations: Ternary operations are achieved through conditionals. Achieve ternary operations through conditionals when you want to assign a value to a variable based on a condition. This is typically done using constructs like “variable=value if condition else other_value.“
- Command Operators: Control command execution using command operators (;, &, |). These operators allow you to execute multiple commands sequentially (;), in the background (&), or in a pipeline (|) to perform complex tasks.
- Redirection Operators: Manage input and output streams of commands with redirection operators (>, >>, <, |). They enable you to redirect command output to files (> and >>), provide input from files (<), or create command pipelines (|) for more advanced data processing and handling.
Understanding and using these operators, you can control program flow, handle conditions, and manipulate data according to your specific requirements.
Operators in Shell Scripts with Practical Examples
Bash provides several types of operators that allow you to perform various operations within shell scripts. Here I will talk about six different types of Bash operators with their relevant examples. Don’t forget to run the code in your terminal to reinforce your understanding.
A. Bash Arithmetic Operators
In Bash scripting, there are several arithmetic operators that allow you to perform mathematical operations on numerical values.
There are eight common arithmetic operators in most programming languages, including Bash scripting.
Here’s a table listing the common arithmetic operators in Bash scripting, along with their descriptions, examples, and meanings:
Operator | Description | Example | Meaning |
+ | Addition | sum=$((a + b)) | Adds the right operand to the left. |
– | Subtraction | diff=$((a – b)) | Subtracts the right from the left. |
* | Multiplication | product=$((a * b)) | Multiplies the left and right values. |
/ | Division | quotient=$((a / b)) | Divides the left by the right. |
% | Modulus (Remainder) | remainder=$((a % b)) | Returns the remainder of division. |
** | Exponentiation (Power) | power=$((a ** b)) | Raises left operand to the power of the right. |
++ | Increment | a=$((a + 1)) | Increases the value of a by 1. |
— | Decrement | b=$((b – 1)) | Decreases the value of b by 1. |
Now, To understand the role of bash operators in the bash script, copy the script given below and run it in the terminal:
#!/bin/bash
# Read user inputs
read -p 'Enter the first number (a): ' a
read -p 'Enter the second number (b): ' b
# Perform arithmetic operations
addition=$((a + b))
echo "The sum of 'a' and 'b' equals $addition"
subtraction=$((a - b))
echo "The result of subtracting 'b' from 'a' is $subtraction"
multiplication=$((a * b))
echo "When 'a' is multiplied by 'b', the result is $multiplication"
division=$((a / b))
echo "When 'a' is divided by 'b', the quotient is $division"
modulus=$((a % b))
echo "The remainder when 'a' is divided by 'b' is $modulus"
# Increment and Decrement operators
((++a))
echo "Using the increment operator on 'a' leads to the new value a = $a"
((--b))
echo "When the decrement operator is used on 'b', the updated value is b = $b"
This Bash script reads two user inputs, a and b. It then performs various arithmetic operations on these numbers: addition, subtraction, multiplication, division, and modulus. Then the echo command displays the results of these operations. Additionally, the script demonstrates the use of the increment operator (++a), which increases the value of a by 1, and the decrement operator (–b), which decreases the value of b by 1, and prints the updated values of a and b after applying these operators.
For the given values of a and b, which are 10 and 3 respectively, this Bash script performs a series of arithmetic operations. It calculates the sum of a and b as 13, the result of subtracting b from a as 7, and the product of a and b as 30. It also determines the quotient when a is divided by b (3) and the remainder when a is divided by b (1). Furthermore, it demonstrates the use of increment and decrement operators, which increment a to 11 and decrement b to 2.
B. Logical Operators in Bash Scripting
Logical operators are used to perform logical operations on expressions or conditions. In Bash scripts, there are several types of logical operators that allow you to perform various logical operations. The primary types of logical operators in Bash include:
1. “&& (AND)” Logical Operator
The && operator in Bash is the logical AND operator. It combines two commands or conditions in such a way that the second command is executed only if the first command succeeds, which means it returns a zero exit status. However, If the first command fails (returns a non-zero exit status), the second command is not executed.
The basic syntax for the && operator:
command1 && command2
command1: The executable first command.
command2: The executable second command if command1 succeeds.
Run the following code to check if file is exist or not in a directory and understand the functionality of the AND operator:
#!/bin/bash
# Check if a file exists and then print a message
if [ -e "myfile.txt" ] && echo "File exists"; then
echo "File check was successful"
else
echo "File does not exist"
fi
In this example, the [ -e “myfile.txt” ] checks if the file myfile.txt exists. If it does, the echo “File exists” command is executed, and then “File check was successful” is printed. However, If the file does not exist, the second command is not executed, and “File does not exist” is printed.
As the bash file doesn’t find myfile.txt in the current directory, the code returns “File does not exist” to the command line.
2. “|| (OR)” Logical Operator
The || operator in Bash is the logical OR operator. It combines two commands or conditions in such a way that the second command is executed only if the first command fails, which means it returns a non-zero exit status. If the first command succeeds (returns a zero exit status), the second command is not executed.
The syntax for the || operator is as follows:
command1 || command2
command1: The first command to be executed.
command2: The second command to be executed if command1 fails.
Here’s an example to demonstrate the overall concept.
Let’s say you want to check a file if it is exist or not using OR operator, run the following code:
#!/bin/bash
# Check if a file exists and print a message if it doesn't
[ -e "myfile.txt" ] || echo "File does not exist"
In the given code, [ -e “myfile.txt” ] checks if the file myfile.txt exists. If it does not exist, the echo “File does not exist” command is executed, and the message “File does not exist” is printed. However, If the file exists, the second command is not executed.
3. “! (NOT)” Logical Operator
The ! operator in Bash is the logical NOT operator. It negates the exit status of a command or condition. If a command succeeds (returns a zero exit status), applying ! to it will make it fail (return a non-zero exit status), and vice versa.
Here’s the syntax for the ! operator:
! command
Now check if a file exists or not using the NOT operator with script given below:
#!/bin/bash
# Check if a file does not exist using the NOT operator
if ! [ -e "non_existent_file.txt" ]; then
echo "File does not exist"
else
echo "File exists"
fi
In the given code, [ -e “non_existent_file.txt” ] checks if the file non_existent_file.txt exists. The ! operator is used before the condition to negate it. So, if the file does not exist (i.e., the condition is true after negation), the message “File does not exist” is printed. However, If the file exists (i.e., the condition is false after negation), the else block is executed, and “File exists” is printed.
C. Bash Relational AKA Comparison Operators
In Bash, relational operators are used to compare values or expressions. These operators allow you to make comparisons and decisions based on the relationship between values.
In Bash, relational operators primarily work with integer values and comparisons. They are not designed to directly compare other data types, such as strings or floating–point numbers. However, you can compare the string value with different approaches, like using the mathematical syntax (eg. = or ==). Firstly, let’s look at the commonly used operator for integer comparison.
1. For Numeric Comparisons:
In Bash, you can use the following relational operators for numeric comparisons:
Operator | Description | Example | Meaning |
-eq | Equal to | [ “$a” -eq “$b” ] | True if both values are equal. |
-ne | Not equal to | [ “$a” -ne “$b” ] | True if values are not equal. |
-lt | Less than | [ “$a” -lt “$b” ] | True if the first value is less than the second. |
-le | Less than or equal to | [ “$a” -le “$b” ] | True if the first value is less than or equal to the second |
-gt | Greater than | [ “$a” -gt “$b” ] | True if the first value is greater than the second. |
-ge | Greater than or equal to | [ “$a” -ge “$b” ] | True if the first value is greater than or equal to the second. |
++ | Increment | a=$((a + 1)) | Increases the value of a by 1. |
— | Decrement | b=$((b – 1)) | Decreases the value of b by 1. |
Below, you’ll find a practical illustration showcasing the concept of using those operators in your bash code:
#!/bin/bash
# Define two integer variables
num1=$1
num2=$2
# Check if num1 is equal to num2
if [ "$num1" -eq "$num2" ]; then
echo "num1 is equal to num2."
else
# Check if num1 is greater than num2
if [ "$num1" -gt "$num2" ]; then
echo "num1 is greater than num2."
else
echo "num1 is less than num2."
fi
fi
First, This Bash script takes two integer values as command–line arguments and assigns them to the variables num1 and num2. Next, It employs the -eq operator to check if num1 equals num2. If they are equal, it prints ‘num1 is equal to num2.’ However, if they are not equal, it utilizes the -gt operator to determine if num1 is greater than num2. If num1 is indeed greater, it outputs ‘num1 is greater than num2.’ Otherwise, if num1 is less, it displays ‘num1 is less than num2.’
Firstly, the -eq, -gt operators are only applicable for the integer value. So, the bash code returns an error upon providing the LinuxSimply and 4 as the command line argument. However, the code works smoothly once it gets 4 4 and 4 5 as the command line arguments and returns num1 is equal to num2 and num1 is less than num2 respectively.
2. For String Comparisons:
However, you can not compare two string values using the numeric comparison operators. For comparing string values, you have to follow the operators provided below.
Operator | Description | Example | Meaning |
= | Equal to (within single brackets [ ]) | [ “$string1” = “$string2” ] | True if both strings are equal. |
== | Equal to (within double brackets [[ ]]) | [[ “$string1” == “$string2” ]] | True if both strings are equal. |
!= | Not equal to [ “$string1” != “$string2” ] | [ “$string1” != “$string2” ] | True if strings are not equal. |
< | Less than (lexicographically) | [ “$string1” \< “$string2” ] | True if string1 is less than string2. |
> | Greater than (lexicographically) | [ “$string1” \> “$string2” ] | True if string1 is greater than string2. |
-gt | Compare the lengths of two strings. | [ “${#string1}” -gt “${#string2}” ] | True if string1 is longer than string2. |
-lt | Compare the lengths of two strings. | [ “${#string1}” -lt “${#string2}” ] | True if string1 is shorter than string2. |
-eq | Compare the lengths of two strings.. | [ “${#string1}” -eq “${#string2}” ] | True if string1 has the same length as string2. |
Suppose you want to compare, str1 and str2, with the following string values, follow the script given below:
#!/bin/bash
# Define two string variables
str1=$1
str2=$2
# Check if str1 is equal to str2
if [ "$str1" = "$str2" ]; then
echo "str1 is equal to str2"
else
echo "str1 is not equal to str2"
fi
# Check if str1 is less than str2
if [ "$str1" \< "$str2" ]; then
echo "str1 is less than str2"
fi
# Check if str1 is greater than str2
if [ "$str1" \> "$str2" ]; then
echo "str1 is greater than str2"
fi
# Compare the lengths of str1 and str2
if [ "${#str1}" -gt "${#str2}" ]; then
echo "str1 is longer than str2"
elif [ "${#str1}" -lt "${#str2}" ]; then
echo "str1 is shorter than str2"
else
echo "str1 and str2 have the same length"
fi
The given Bash script takes two string values as command-line arguments and assigns them to the variables str1 and str2. It then performs a series of string comparisons. Firstly, it checks if str1 is equal to str2 using the = operator and prints “str1 is equal to str2” if they are equal, or “str1 is not equal to str2” if they are not.
Next, it uses the < and > operators to determine if str1 is lexicographically less than or greater than str2 and prints the corresponding messages. Finally, it compares the lengths of str1 and str2, printing messages based on whether str1 is longer, shorter, or has the same length as str2.
D. Bash Bitwise Operators
Moving onto the next discussion, Bash bitwise operators manipulate individual bits of binary numbers. They operate at the binary level, performing operations like AND, OR, XOR, complement, left shift, and right shift on the binary representation of numbers. Here’s a brief explanation of each bitwise operator in Bash:
Operator | Description | Meaning |
& | Bitwise AND | Performs binary AND operation bit by bit on the operands. |
| | Bitwise OR | Performs binary OR operation bit by bit on the operands. |
^ | Bitwise XOR | Performs binary XOR operation bit by bit on the operands. |
~ | Bitwise Complement | Performs binary NOT operation bit by bit on the operand. |
<< | Left Shift | Shifts the bits of the left operand to the left by the number of times specified by the right operand. |
>> | Right Shift | Shifts the bits of the left operand to the right by the number of times specified by the right operand. |
++ | Increment | a=$((a + 1)) |
— | Decrement | b=$((b – 1)) |
Here is a sample code provided for illustrating the application of some bitwise operators:
#!/bin/bash
# Bitwise AND operator (&)
result_and=$((5 & 3)) # 5 in binary: 0101, 3 in binary: 0011
echo "Bitwise AND result: $result_and"
# Bitwise OR operator (|)
result_or=$((5 | 3)) # 5 in binary: 0101, 3 in binary: 0011
echo "Bitwise OR result: $result_or"
# Bitwise XOR operator (^)
result_xor=$((5 ^ 3)) # 5 in binary: 0101, 3 in binary: 0011
echo "Bitwise XOR result: $result_xor"
# Bitwise complement operator (~)
result_complement=$((~5)) # 5 in binary: 0101
echo "Bitwise complement result: $result_complement"
# Bitwise left shift operator (<<)
result_left_shift=$((5 << 2)) # Left shift 5 by 2 positions
echo "Bitwise left shift result: $result_left_shift"
# Bitwise right shift operator (>>)
result_right_shift=$((20 >> 2)) # Right shift 20 by 2 positions
echo "Bitwise right shift result: $result_right_shift"
This Bash script demonstrates the use of bitwise operators. Firstly, it computes the bitwise AND (&) of 5 and 3, which involves comparing their binary representations (5 in binary: 0101, 3 in binary: 0011). Subsequently, it calculates the bitwise OR (|) of the same numbers. Thirdly, it computes the bitwise XOR (^). After that, it applies the bitwise complement (~) to 5. Finally, it performs bitwise left shift (<<) on 5 by 2 positions, and bitwise right shift (>>) on 20 by 2 positions. The script then displays these results using the echo command.
This Bash script demonstrates the use of various bitwise operators and explanations of the outcomes are listed below:
- Bitwise AND result: 1
- Compares binary representations of 5 (0101) and 3 (0011).
- Compares each bit position: 0 & 0 = 0, 1 & 0 = 0, 0 & 1 = 0, 1 & 1 = 1.
- Result: 0001 in binary, which is 1 in decimal.
- Bitwise OR result: 7
- Compares binary representations of 5 (0101) and 3 (0011).
- Compares each bit position: 0 | 0 = 0, 1 | 0 = 1, 0 | 1 = 1, 1 | 1 = 1.
- Result: 0111 in binary, which is 7 in decimal.
- Bitwise XOR result: 6
- Compares binary representations of 5 (0101) and 3 (0011).
- Compares each bit position: 0 ^ 0 = 0, 1 ^ 0 = 1, 0 ^ 1 = 1, 1 ^ 1 = 0.
- Result: 0110 in binary, which is 6 in decimal.
- Bitwise Complement result: -6
- Takes the bitwise complement of 5 (0101).
- Inverts each bit: 0 becomes 1, and 1 becomes 0.
- Result: 1010 in binary, which is -6 in two’s complement representation.
- Bitwise left shift result: 20
- Left-shifts the binary representation of 5 (0101) by 2 positions.
- Adds zeros on the right: 010100 in binary.
- Result: 20 in decimal.
- Bitwise right shift result: 2
- Right-shifts the binary representation of 20 (10100) by 2 positions.
- Discards the least significant bits: 0010 in binary.
- Result: 2 in decimal.
E. Bash File Test Operators
Bash File Test Operators are used to check various attributes of files and directories in a Bash script. These operators help you determine whether a file exists if it’s a regular file or a directory, its permissions, modification times, and more.
Here is a list of file test operators commonly used:
Operator | Description | Example | Meaning |
-e filename | Checks if filename exists. | [ -e file.txt ] | True if the file file.txt exists, false otherwise. |
-f filename | Tests if filename is a regular file. | [ -f file.txt ] | True if file.txt is a regular file, false otherwise. |
-d dirname | Checks if dirname is a directory. | [ -d directory ] | True if the directory is a directory, false otherwise. |
-s filename | Verifies if filename is not empty. | [ -s file.txt ] | True if file.txt exists and is not empty, false otherwise. |
-r filename | Checks if filename is readable. | [ -r file.txt ] | True if file.txt is readable, false otherwise. |
-w filename | Tests if filename is writable. | [ -w file.txt ] | True if file.txt is writable, false otherwise. |
-x filename | Checks if filename is executable. | [ -x script.sh ] | True if script.sh is executable, false otherwise. |
-h filename | Checks if filename is executable. | [ -h link.txt ] | True if link.txt is a symbolic link, false otherwise. |
-L filename | Similar to -h, checks if filename is a symbolic link. | [ -L link.txt ] | True if link.txt is a symbolic link, false otherwise. |
-L filename | Checks if filename is newer. | [ -N file.txt ] | True if file.txt is newer than the last read, false otherwise. |
-o filename | Tests if filename is owned by the user. | [ -o file.txt ] | True if file.txt is owned by the user, false otherwise. |
The file test operators are used in conditional statements to check the attributes and conditions of files and directories in Bash scripts. Here is a sample code that has been demonstrated below to give you an overall idea:
#!/bin/bash
# Read file name from the user
read -p 'Enter the name of the file: ' UserFileName
# Check if the file exists
if [ -e $UserFileName ]
then
echo "The file exists."
else
echo "The file does not exist."
fi
# Check if the file is not empty
if [ -s $UserFileName ]
then
echo "The provided file is not empty."
else
echo "The provided file is empty."
fi
# Check if the file has read permissions
if [ -r $UserFileName ]
then
echo "The provided file has read permissions."
else
echo "The provided file does not have read permissions."
fi
# Check if the file has write permissions
if [ -w $UserFileName ]
then
echo "The provided file has write permissions."
else
echo "The provided file does not have write permissions."
fi
# Check if the file has execute permissions
if [ -x $UserFileName ]
then
echo "The provided file has execute permissions."
else
echo "The provided file does not have execute permissions."
fi
This Bash script allows the user to input a file name. It then employs various file test operators to determine attributes and permissions associated with the provided file. Firstly, it checks if the file exists using -e and displays whether it exists or not. Next, it checks if the file is empty with -s and provides feedback accordingly.
Subsequently, The script proceeds to assess whether the file has read permissions -r, write permissions -w, and execute permissions -x, and it reports the findings for each permission type. Then, the output messages display the existence of the file, its emptiness, and its read, write, and execute permissions status based on the user’s input.
Finally, Upon executing the ls-l command, as you can see a list of files and folder names in the current directory. From the image given above, first of all, there is a LinuxSimply,txt file where “Hello World” text line is written.
Now if you run the second given command, you will see the code return its output by stating that The file exists, The provided file is not empty, The provided file has read permissions, The provided file has write permissions, The provided file does not have execute permissions respectively and validate the information given by the ls-l command.
F. Bash Unary Operators
Bash Unary Operators are fundamental components of the Bash scripting language that operate on a single operand. These operators allow you to perform various tasks, such as incrementing or decrementing variable values, inverting logical or bitwise values, and indirectly accessing variables using references.
The most common unary operators in Bash are given in the following table:
Operator |
Description | Example | Meaning |
Increment (++) | Increases the value of a variable by 1 | x++ | Add 1 to the value of ‘x’ |
Decrement (–) | Decreases the value of a variable by 1 | y– | Subtract 1 from the value of ‘y’ |
Negation (-) | Reverses the sign of a numeric value | -n | Flip the logical value of the condition |
Logical NOT (!) | Inverts the logical value of a condition | !true | Reverse the logical value of a condition |
Indirection (*) | Inverts the bits of a numeric value | ~5 | Invert all bits of the numeric value |
Indirection (*) | Retrieves the value of a variable indirectly | varname=”x”<br>${!varname} | Get the value of the variable specified indirectly by ‘varname’ |
This table provides a clear overview of each unary operator’s description, an example of its usage, and its comprehensive meaning.
Here, I am going to provide a sample script. The script demonstrates the use of various unary operators in Bash, including increment (++), decrement (–), negation (-), logical NOT (!), bitwise NOT (~), and indirection (*). It initializes variables with different values and then applies these operators to showcase their functionality.
#!/bin/bash
# Initialize variables
x=5
y=10
n=3
is_true=true
bit_value=7
varname="z"
# Increment operator (++)
echo "x before increment: $x"
((x++))
echo "x after increment: $x"
# Decrement operator (--)
echo "y before decrement: $y"
((y--))
echo "y after decrement: $y"
# Negation operator (-)
echo "n before negation: $n"
((-n))
echo "n after negation: $n"
# Logical NOT operator (!)
echo "is_true before logical NOT: $is_true"
! $is_true
echo "is_true after logical NOT: $is_true"
# Bitwise NOT operator (~)
echo "bit_value before bitwise NOT: $bit_value"
((~bit_value))
echo "bit_value after bitwise NOT: $bit_value"
# Indirection operator (*)
z="Indirection Example"
echo "varname before indirection: $varname"
indirect_var="${!varname}"
echo "indirect_var after indirection: $indirect_var"
The Bash script showcases the usage of various unary operators. Firstly, It begins by initializing several variables with different values. Secondly, It demonstrates the increment (++) and decrement (—) operators, which respectively increase and decrease the values of x and y. The negation (–) operator reverses the sign of n.
Furthermore, The logical NOT (!) operator inverts the boolean value of ‘is_true.’ The bitwise NOT (~) operator inverts the bits of ‘bit_value.’ Finally, the indirection (*) operator indirectly accesses a variable by referring to its name stored in varname, displaying the value of ‘indirect_var.’
When the provided Bash script is executed, it shows the initial values and the impact of the unary operators used in the script. x increments from 5 to 6, y decrements from 10 to 9, n is negated to -3, ‘is_true’ remains true but is logically inverted, ‘bit_value‘ undergoes bitwise inversion from 7 to -8, and the indirection operator retrieves the value of z, resulting in “Indirection Example.”
Conclusion
In our comprehensive overview of the Bash operator, I have provided several demonstrations, from arithmetic operators for numerical manipulations to logical operators for decision–making, and file test operators for managing files and directories, I’ve covered it all. However, If you have any confusion or queries related to the bash operator, don’t forget to comment below. Thank you!
People Also Ask
What is ‘|’ in bash?
In Bash, the ‘|‘ (pipe) symbol passes the output of one command as input to another command, allowing for the chaining of commands together in a pipeline.
What does <<< in bash do?
In Bash, ‘<<<‘ is used to redirect a string as input to a command. It allows you to pass a string directly to a command without the need for an external file or command substitution.
What is $* in Unix?
In Unix, $* represents all the command–line arguments passed to a script or command as a single string, separated by spaces.
What does grep do?
grep is a command–line tool in Unix for searching text patterns or regular expressions within files. It scans file contents and displays lines containing the specified pattern, making it useful for text searching and filtering.
Related Articles
- Arithmetic Operators in Bash
- Bash Logical Operators
- Unary Operators in Bash
- Usage of Ternary Operator in Bash [with 2 Examples]
- Bitwise Operators in Bash Scripting
- An Overview of Bash Comparison [Conditional] Operators
<< Go Back to Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners