Bash 脚本中的三元运算符

Muhammad Husnain 2022年7月18日
Bash 脚本中的三元运算符

本文是 Bash 脚本中条件运算符(也称为三元运算符)的简单指南。

Bash 脚本中的三元运算符

三元或条件运算符通常用作 if..else 语句的内联替换。在大多数编程语言中,它使用两个符号 ?:来构成一个条件语句。


ReturnValue = expression ? trueValue : falseValue

Bash 没有对条件运算符的直接支持。但是,可以使用以下条件语句来实现此三元运算。

[conditional-expression] && Result1|| Result2

这个表达式被评估为好像 conditional-expressiontrue,然后&&运算符将被操作,Result1 将是答案。但是如果 conditional-expressionfalse,那么第二个逻辑运算符||将运行,它会给出 Result2 作为答案。


echo "Enter Your Age: "
read a;
[[ $a == 25 ]] && res="yes" || res="no"
echo "Elgibility: $res" ;


在 Bash 脚本中实现三元运算符


Muhammad Husnain avatar Muhammad Husnain avatar

Husnain is a professional Software Engineer and a researcher who loves to learn, build, write, and teach. Having worked various jobs in the IT industry, he especially enjoys finding ways to express complex ideas in simple ways through his content. In his free time, Husnain unwinds by thinking about tech fiction to solve problems around him.


相关文章 - Bash Operator