How to Use Ternary Operator (?:) in Bash

The Ternary Operator, also known as the conditional operator, is an important feature of Bash Linux that allows developers to perform conditional operations in a single line of code. It allows users to write conditional statements in a more concise and readable way. This article will discuss in detail the ternary operator and how a user can utilize it in bash scripting using the following outline.

  • How a Ternary Operator Works?
  • Examples of Ternary Operator

How a Ternary Operator Works?

The syntax of the Ternary Operator in Bash Linux is as follows:

(condition) ? expression1 : expression2

A condition (a Boolean expression) evaluates to true, and expression1 is executed; otherwise, expression2 is executed.

Examples of Ternary Operator

This section will discuss a few examples of ternary operators for better understanding.

Example 1: Comparing Two Variables

If a user wants to compare two variables using a ternary operator, then it can be done by following the below bash script:

#!/bin/bash
a=10
b=20
max=$((a>b ? a : b))
echo $max

Code Explanation

  • Two variables, a and b, are being compared using the Ternary Operator. 
  • If a is greater than b, a is assigned to the max. Otherwise, b is assigned to the max. 

Code Execution

The output of the code can be seen by executing the bash script below:

$ bash ternary_op.sh

The variable ‘a’ has a value of 10 whereas the variable ‘b’ has a value of 20 which is greater than variable a, so its value is printed on the terminal.

Example 2: Comparing Three Variables

Similarly, a user can compare more than two variables as well using the ternary operator as shown below:

#!/bin/bash
a=10
b=20
c=30
max=$(((a>b)?(a>c?a:c):(b>c?b:c)))
echo $max

Code Explanation

  • Three variables, a, b, and c are being compared having different values. 
  • If a is greater than b and c, a is assigned to the max. 
  • If b is greater than a and c, b is assigned to the max. 
  • Otherwise, c is assigned to the max. In this case, the output will be 30.

Code Execution

The code output can be seen by executing the bash script below:

$ bash ternary_op.sh

Variable ‘a’ has a value of 10, variable ‘b’ has a value of 20, and variable ‘c’ has a value of 30. A variable c has the greatest value among the three, so its value will be printed on the terminal.

Conclusion

Ternary Operator is a powerful feature of Bash Linux that allows users to perform conditional operations in a single line of code. It can be an alternative option for an If else statement, and the code written in it will be short. Detailed information regarding the ternary operator has been provided in this article, along with examples.