-
在其他语法中常见的三目运算方式:
表达式 ? 表达式 : 表达式 ; -
在
shell中也有类似的方式:command1 && command2 || command3如果
command是一连串的组合,那么可以使用{ }将commands括起来。注意:代码块若用在函数中,{ }最后一个必须是;command1 && { command2_1; command2_2; command2_3; } || { command3_1; command3_3; command3_3; } -
举例
#!/bin/bash res="mp-weixin" iswx=$([[ $res =~ "weixin" ]] && echo 1 || echo 0) echo "$iswx"# 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
Shell 三目运算(详细案例)
最新推荐文章于 2026-03-26 12:42:18 发布
本文详细介绍了shell编程中如何使用三目运算符(条件表达式)`command1&&command2||command3`,以及如何在函数中嵌套命令块。通过实例展示了文件存在检查、输出信息控制和IP地址读取的应用。
&spm=1001.2101.3001.5002&articleId=132297103&d=1&t=3&u=228ed9bc9ab8493aa6bd8ee550ba12e3)
446

被折叠的 条评论
为什么被折叠?



