当前位置:网站首页>一行代码实现shell if else逻辑
一行代码实现shell if else逻辑
2022-06-12 12:39:00 【Hello_wshuo】
前言
前几天学习 shell 脚本,发现这种好用的写法,简单记录一下。
if else 一行实现
if [ 1=1 ] ;then echo "条件成立";else echo "条件不成立"; fi
关键点就在在代码块分支逻辑间位置加上;就可以实现逻辑写到一行
|| && 实现if else逻辑
[email protected]:~$ function test
> {
> echo 1
> }
[email protected]D-114-36:~$ test && echo "条件成立" || echo "条件不成立"
1
条件成立
利用 && 和 || 判断逻辑顺序实现if else逻辑,当 test 返回值为1,则执行 并且 逻辑,如果返回为0 则执行 或 逻辑。
这里利用函数,主要是if逻辑不能作为执行语句从而获得返回值。
不过这里有两个问题:
- 输出了函数返回值
- 每次判断逻辑声明一个函数反而臃肿
针对第一个问题可以修改为:
[email protected]:~$ test &>/dev/null && echo "条件成立" || echo "条件不成立"
条件成立
针对第二个问题,可以使用 expr命令:
[email protected]:~$ expr 1 = 1 &>/dev/null && echo "条件成立" || echo "条件不成立"
条件成立
[email protected]:~$ expr 1 = 2 &>/dev/null && echo "条件成立" || echo "条件不成立"
条件不成立
expr 同样也可以判断字符串是否相等,也可以判断数值大小,可以满足所有判断条件
边栏推荐
- JS method of exporting DOM as picture
- 轻量化---Project
- 【VIM】.vimrc配置,已经安装Vundle,YoucompleteMe
- Index changes of seed points in ITK original image after ROI and downsampling
- 二叉树(思路篇)
- VTK three views
- [VIM] VIM plug-in youcompleteme configuration file
- SWI-Prolog的下载与使用
- Take the web page animation effects that can be used. Don't you come and have a look?
- Influxdb2.x benchmark tool - influxdb comparisons
猜你喜欢

You can't just use console Log ()?

轻量化---Project

Safety KNN

Geek challenge 2021 Web
![[C language] keyword static & Multi file & guessing game](/img/82/fa3556522531f83e95938fc4efbf1e.png)
[C language] keyword static & Multi file & guessing game

C语言进阶篇——深度解剖数据在内存中的存储(配练习)

this.$ How to solve the problem when refs is undefined?

C语言进阶篇——万字详解指针和qsort函数

Iterator, generator generator details

Advanced chapter of C language -- ten thousand words explanation pointer and qsort function
随机推荐
轻量化---Project
检测vector是否有交集
Constant time delete / find any element in array
Boot entry directory
Typescript and abstract classes
Is yuancosmos a short-term speculation or a future trend?
VTK three views
元宇宙是短炒,还是未来趋势?
提升管道效率:你需要知道如何识别CI/CD管道中的主要障碍
Advanced chapter of C language -- ten thousand words explanation pointer and qsort function
Imx6 uboot add lvds1 display
Robot Jacobian solution
Bat interview & advanced, get interview materials at the end of the text
C语言进阶篇——深度解剖数据在内存中的存储(配练习)
Differences and recommended uses of VaR, let and const (interview)
The 4th Zhejiang CTF preliminary contest web pppop
Detect whether the vector has an intersection
SEO optimization of web pages
Newton method for solving roots of polynomials
JS string array converted to numeric array and how to add the numbers in the array