shell命令返回值判断的方法实现
沙雕mars · 278浏览 · 发布于2022-02-24
本文主要介绍了shell命令返回值判断的方法实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
1.判断命令是否存在
优雅方法1
首先,检查命令是否有效的惯用方法直接在if语句中。
if command; then echo notify user OK >&2 else echo notify user FAIL >&2 return -1 fi
(良好做法:使用>&2将消息发送给stderr。)
优雅方法2
将通用逻辑转移到共享函数中。
优雅方法3
installed () { command -v "$1" >/dev/null 2>&1 } if installed <command1> then <command1> xx else <command1> xxx fi
2.返回错误退出
1.|| exit退出
command1 || exit command2 || exit command3 || exit
2.使用-e
$ bash -e xx.sh #!/bin/bash -e xx.sh command1 command2 command3
3.set -e
$ bash xx.sh #!/bin/bash set -e command1 command2 command3
3.返回错误提示
一般方法:
方法1
if do some command; then echo notify user OK else echo notify user fail exit 255 # exit code must be unsigned short fi
方法2
do some command if [ $? -eq 0 ]; then echo notify user OK else echo notify user FAIL return -1 fi
优雅方法
方法1
die() { local message=$1 echo "$message" >&2 exit 1 } command1 || die 'command1 failed' command2 || die 'command2 failed' command3 || die 'command3 failed'
方法2(推荐)
warn () { echo "$@" >&2 } die () { status="$1" shift warn "$@" exit "$status" } do some command && echo notify user OK || die 255 Notify user fail
相关推荐
将Fedora 29升级到Fedora 30
吴振华 · 702浏览 · 2019-05-14 22:00:02
有效避免数据丢失!Redis持久化方案选择详解
manongba · 915浏览 · 2019-05-15 10:58:03
使用Nginx反向代理到go-fastdfs
iamitnan · 724浏览 · 2019-05-23 13:42:00
利用VLC搭建组播流服务器
追忆似水年华 · 2691浏览 · 2019-06-14 11:27:06
如何设计一个优秀的分布式系统?重要因素、工具、策略都在这里
chenguangming9 · 712浏览 · 2019-06-18 11:00:10
用Bash脚本监控Linux上的内存使用情况
吴振华 · 972浏览 · 2019-06-24 11:27:02
分类专栏
最新发布
最热排行
0评论