FUNDAMENTALS A Complete Guide for Beginners
A ternary operator is a concise way to express a conditional (if-else) statement in Bash. It’s called “ternary” because it involves three parts: a condition, an expression to evaluate if the condition is true, and an expression to evaluate if the condition is false. The Bash ternary operator, denoted by the ? : symbol. It allows the program to make decisions based on a condition and execute different code blocks accordingly.
In this guide, I’m going to show you how to use the ‘ternary’ operator in bash. So let’s start!
What is Ternary Operator in Bash Script?
The ternary operator in bash is a shorthand for if-else statements that return a value.
The common syntax it follows in Bash is:
(condition) ? (if_true) : (if_false)
Here, the condition is the expression that is to be evaluated. If the condition is true (zero), then the value will be returned. Otherwise, the value is set to false (one).
It is important to note that, the ternary operator in bash is only limited to the arithmetic expression of the bash script. The operator will return only 0 if the condition is true or 1 otherwise. To make the code more resourceful you can employ the if-else statement along with the ternary operator.
How to Use the Ternary Conditional Operator in Bash Script?
Let’s say you have two numbers, a and b, and you want to figure out the maximum value among them. To find the maximum value among two numbers, you can directly use the ternary operator syntax as follows:
#!/bin/bash
read -p "Enter the first number: " a
read -p "Enter the second number: " b
z=$((a > b ? a : b))
echo "The maximum number among those two given number is: $z"
This script prompts the user to input two numbers, ‘a’ and ‘b’, using the read -p command. It then employs the Bash ternary operator to compare ‘a’ and ‘b’. If ‘a’ is greater than ‘b’, it assigns the value of ‘a’ to the variable ‘z’. If ‘a’ is not greater than ‘b’, it assigns the value of ‘b’ to ‘z’. Finally, the script displays the maximum number among the two given numbers using the echo command.
As you can see from the above image, the script returns the maximum value for both cases.
Alternatively, you can also define the variable z inside the double parentheses:
((z = a > b ? a : b))
echo "$z"
It is possible to use the let command instead of double parentheses when performing arithmetic evaluation. For example, you can use the let command to attribute the result of ternary expressions to a variable:
let z="(a > b) ? a : b"
echo "$z"
Finally, the assignment can also be placed within quotations:
let "z = (a > b) ? a : b"
echo "$z"
2 Examples of Ternary Operator in Bash Scripting
In the following section, I will dive into two different examples of using ternary operator in bash scripting.
Example 1: Ternary Operator in Arithmetic Evaluation
Arithmetic evaluation is a powerful feature that allows user to perform mathematical operations directly within the scripts. The double parentheses ((…)) are commonly used to denote arithmetic evaluation. Within these parentheses, you can utilize the ternary operator to evaluate arithmetic expressions. As Bash’s ternary expression is only for arithmetic expression, it can’t accept any string value. The following script shows an example of its usage:
#!/bin/bash
read -p "Enter the input value: " x
#incorporating the ternary operator
output=$((x % 2 == 0 ? 1 : 0))
#using if-else loop to make decision
if [ "$output" -eq 1 ]; then
echo 'The number is even'
else
echo 'The number is odd'
fi
This bash script will ask the user to enter a number and store it in x. Then, it’ll use a modulus operation x% 2 == 0
to check if the remainder of x divided by 2 is 0. If it’s true, 1 will be assigned to ‘output’. Otherwise, 0 will be assigned to the ‘output’ variable. After that, it’ll use the ‘if-else’ condition to check the ‘output’ variable. If ‘output’ equals ‘1’, it’ll show “The number is Even”. Otherwise, it’ll print “Number is odd”.
When 9 and 6 are given as input, the code prints whether odd or even on the terminal.
Example 2: Nested Ternary Expressions to Compare Integer Number
An expression that is inside another expression is called a nested expression. Similarly, ternary expressions can also be nested by placing another ternary operator within the true or false branch of an outer ternary operator.
For instance, the nested ternary operator can be used to figure out the maximum value of three different numbers in a certain way.
#!/bin/bash
# Prompt the user to input values for 'a', 'b', and 'c'
read -p "Enter the value of 'a': " a
read -p "Enter the value of 'b': " b
read -p "Enter the value of 'c': " c
# Using the Bash ternary operator
max=$(( a > b ? ( a > c ? a : c) : (b > c ? b : c) ))
# Display the maximum value to the user
echo "The maximum value among $a, $b, and $c is: $max"
In the above script, the ternary operator is structured to compare a with b and c. If a is greater than b, it then compares a with c. If a is the largest, it assigns a as the maximum. Otherwise, it evaluates b against c and assigns the largest of the two as the maximum. The result is stored in the variable ‘max‘. Finally, the script displays the maximum value among a, b, and c using the echo command.
As you can see from the above image, the script returns the highest number among three input numbers.
Order of Ternary Operator Evaluation
The order of ternary operator evaluation proceeds sequentially from right to left. The rightmost condition or operation is evaluated first, followed by subsequent expressions or conditions. For example, in (( expr1 ? expr2 : expr3 ? expr4 : expr5 ))
, the expr3 will be evaluated first. If expr3 is true, expr4 is evaluated, and if expr3 is false, expr5 will be returned. Next, if expr1 is true the expr2 will be the final result, if false the output of the expr3 ? expr4 : expr5 will be returned.
Let’s see an example of comparing three integers to find the maximum value among them and learn the order of evaluation of the ternary operator in bash:
#!/bin/bash
#using read -p command to take the user value
read -p "Enter the first value: " var1
read -p "Enter the second value: " var2
read -p "Enter the third value: " var3
#employing the ternary operator
var=$((var1 > var2 ? var1 : var2 > var3 ? var2 : var3))
#printing the output
echo "The maximum value among the three numbers is: $var"
First, the expression compares var2 with var3. If var2 is greater than var3, it returns var2 as a greater value, var3 otherwise. Then the code evaluates whether var1 is greater or var2. If the result is true, the code assigns var1 to var, if not it will assign the result of var2 > var3 ? var2 : var3
to the var variable.
Among three different numbers 3, 6, 1, the script displays 6 as the maximum.
Conclusion
The ternary operator is a powerful tool that can be used to write more concise and readable Bash code. If you use them correctly, they can also make your code easier to read. However, it can also be confusing, especially for new Bash users. If you are new to Bash, I recommend that you start by using if-else statements and then move on to the ternary operator once you are more comfortable with Bash programming. Still, if you have any questions or queries related to ternary operator in Bash, feel free to comment below. Thank You!
People Also Ask
What is the ternary operator in a variable declaration?
The ternary operator is a compact statement used to assign value to a variable according to a condition. It is denoted by ?: and used in various programming languages for concise conditional assignments. The ternary operator is used in the following way: variable = (condition ? value_if_true : value_if_false);
Is ternary operator an expression?
Yes, ternary operator is an expression. The ternary operator evaluates to a value based on the condition provided. It is a short-term expression for a conditional statement. It is a compact and powerful way to make decisions within code.
Is ternary operator a binary operator?
A ternary operator is a non-binary operator. It is referred to as a ternary because it takes three arguments (condition, value if true, and value if false). This makes it different from traditional binary operators and adds to its conditional nature. The condition is represented as condition?value_if_true:value_if_false
Is the ternary operator faster than if-else?
In most cases, the speed difference is really small and depends on the language you’re using. But the fact that the operator is compact makes it look like it’s faster. This could make it easier to optimize your code and make it easier to read, especially if you’re using a language that has a good implementation of it. In some cases, the compiler or interpreter could make the operator faster than an if statement, so you might think it’s faster.
How do you assign a value to a ternary operator?
In bash programming languages, you assign a value to a ternary operator by using it within an expression. The format generally follows the syntax: variable = (condition ? value_if_true : value_if_false);
Here, the condition is evaluated. If true, value_if_true is assigned to the variable; if false, value_if_false is assigned. This statement provides a concise way to conditionally assign a value to a variable based on a particular condition.
How many ternary operators are there?
The ternary operator is usually considered to be a single operator, but it can also be used more than once in one expression. In the context of programming, it is often referred to as the conditional operator (ternary), which is a simple operator that takes 3 operands to decide on a condition.
Related Articles
- Arithmetic Operators in Bash
- Bash Logical Operators
- Unary Operators in Bash
- Bitwise Operators in Bash Scripting
- An Overview of Bash Comparison [Conditional] Operators
<< Go Back to Bash Operator | Bash Scripting Tutorial