Ternary Operator
Learn what the ternary operator is and how it works in Bash.
We'll cover the following
Ternary operator
The ternary operator is also known as the conditional operator and ternary if. It first appeared in the programming language ALGOL. The operator turned out to be convenient and many programmers liked it. The languages of the next generation, BCPL and C, inherited the ternary if. It later came to almost all modern languages, including C++, C#, Java, Python, PHP, and more.
A ternary operator is a compact form of the if
statement.
For example, let’s suppose that our script has the following if
statement:
if ((var < 10))
then
((result = 0))
else
((result = var))
fi
Here, the result
variable is assigned the zero value if var
is less than 10. Otherwise, result
gets the value of var
.
We can get the same behavior using the ternary operator. It looks like this:
((result = var < 10 ? 0 : var))
Run the commands discussed in this lesson in the terminal below.
Get hands-on with 1200+ tech skills courses.