In Linux and Unix-like operating systems, various operators are used in shell commands and scripts to perform different operations.
Most commonly used shell operators:
Arithmetic Operators:
+
(Addition): Used to perform addition in arithmetic operations.-
(Subtraction): Used to perform subtraction.*
(Multiplication): Used for multiplication./
(Division): Used for division.%
(Modulus): Calculates the remainder of a division.Example:
result=$((5 + 3))
echo "Result: $result"
Assignment Operators:
=
(Assignment): Assigns a value to a variable.+=
(Add and Assign): Adds the right-hand value to the variable.-=
(Subtract and Assign): Subtracts the right-hand value from the variable.*=
(Multiply and Assign): Multiplies the variable by the right-hand value./=
(Divide and Assign): Divides the variable by the right-hand value.%=
(Modulus and Assign): Assigns the remainder of the division to the variable.Example:
count=10
count+=5
echo "Count: $count"
Comparison Operators:
=
(Equal to): Tests if two values are equal.!=
(Not Equal to): Tests if two values are not equal.-eq
(Equal): Tests if two integers are equal.-ne
(Not Equal): Tests if two integers are not equal.-gt
(Greater Than): Tests if an integer is greater than another.-lt
(Less Than): Tests if an integer is less than another.-ge
(Greater Than or Equal to): Tests if an integer is greater than or equal to another.-le
(Less Than or Equal to): Tests if an integer is less than or equal to another.Example:
if [ $x -eq $y ]; then
echo "x is equal to y"
fi
Logical Operators:
&&
(Logical AND): Performs an operation if both conditions are true.||
(Logical OR): Performs an operation if either condition is true.!
(Logical NOT): Negates a condition.Example:
if [ $age -ge 18 ] && [ $citizenship = "US" ]; then
echo "You can vote in the US."
fi
String Operators:
=
(Equal to): Tests if two strings are equal.!=
(Not Equal to): Tests if two strings are not equal.-z
(Zero-Length): Tests if a string has zero length (is empty).-n
(Non-Zero Length): Tests if a string has a non-zero length.Example:
if [ "$name" = "Alice" ]; then
echo "Hello, Alice!"
fi
These are the most common operators used in Linux shell scripting. Understanding how to use these operators is essential for creating conditionals, loops, and performing various operations in shell scripts.
Enroll Now