Shell三元表达式

 

Shell三元表达式

 

shell能否实现三元表达式呢?像下面这样:

int a = (b == 5) ? c : d;

实现方法:

a=$([ "$b" == 5 ] && echo "$c" || echo "$d")

原理:

&&的优先级比||高,所以如果前面的&&成功,后面的||就不会执行;相反,后面的||就会执行。

 

 

C/C++、Java、Python 代码中最常见的就是 if else 结构,而最简单的 if else 结构一般多用 条件运算符(三目运算符)来书写,该运算符由问号(?)和冒号(:)组成,其格式如下:

表达式 ? 表达式 : 表达式 ;

等同于C/C++编程语言中的 if 语句:

if (表达式1)
表达式2;
else
表达式3;

shell 脚本
在 bash shell 中也有类似的方式:

command1 && command2 || command3

如果 command 是一连串的组合,那么可以使用 { } 将commands 括起来。

command1 && { command2_1; command2_2; command2_3;} || { command3_1; command3_3; command3_3;

注意:代码块若用在函数中, { } 最后一个必须是 ;

举例:
# fileName 文件不存在,则退出,就可以按照下面方式执行
[ -e $fileName ] || { echo -e "fileName Not existed!"; exit 1; }

#也或者可以增加一些 log 打印信息
[ -e $fileName ] && echo -e "$fileName existed" || { echo -e "$fileName Not existed!"; exit 1; }

#多个命令集合的组合
[ -e $fileName ] && echo -e "$fileName existed"; ehco -e "Other Necessary Information" || { echo -e "$fileName Not existed!"; exit 1; }
[ -e $fileName ] && { echo -e "$fileName existed"; ehco -e "Other Necessary Information"; } || { echo -e "$fileName Not existed!"; exit 1; }

#读取IP地址,若为空,则使用默认IP,否则使用新的IP地址
read -p "Please input Management IP (Default is $DEFAULT_IP): " MGMT_IP
[[ -z $MGMT_IP ]] && { MGMT_IP=$DEFAULT_IP; echo -e "Using default IP $MGMT_IP\n" ;} || DEFAULT_IP=$MGMT_IP

posted @ 2022-12-30 15:36  牧之丨  阅读(743)  评论(0编辑  收藏  举报