Shell 三目运算(详细案例)

简介: Shell 三目运算(详细案例)
  • 在其他语法中常见的三目运算方式:
表达式 ? 表达式 : 表达式 ;
  • 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
目录
打赏
0
1
1
0
268
分享
相关文章
|
10月前
|
Linux C/C++ 开发(学习笔记二):Shell脚本编程案例
Linux C/C++ 开发(学习笔记二):Shell脚本编程案例
141 0
常用的 55 个 Linux Shell 脚本(包括基础案例、文件操作、实用工具、图形化、sed、gawk)
这篇文章提供了55个常用的Linux Shell脚本实例,涵盖基础案例、文件操作、实用工具、图形化界面及sed、gawk的使用。
999 2
Shell基础学习---3、Read读取控制台输入、函数、综合应用案例:归档文件、正则表达式入门(第二天学习)
Shell基础学习---3、Read读取控制台输入、函数、综合应用案例:归档文件、正则表达式入门
157 1
一个案例学习bat和shell脚本的编写
一个案例学习bat和shell脚本的编写
107 0
Shell 三目运算(详细案例)
Shell 三目运算(详细案例)
200 1
|
17天前
|
【linux】Shell脚本中basename和dirname的详细用法教程
本文详细介绍了Linux Shell脚本中 `basename`和 `dirname`命令的用法,包括去除路径信息、去除后缀、批量处理文件名和路径等。同时,通过文件备份和日志文件分离的实践应用,展示了这两个命令在实际脚本中的应用场景。希望本文能帮助您更好地理解和应用 `basename`和 `dirname`命令,提高Shell脚本编写的效率和灵活性。
79 32
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等