shell命令返回值判断的方法实现
目录
1.判断命令是否存在优雅方法1优雅方法2优雅方法32.返回错误退出1.||exit退出2.使用-e3.set-e3.返回错误提示一般方法:优雅方法1.判断命令是否存在
优雅方法1
首先,检查命令是否有效的惯用方法直接在if语句中。
if command; then echo notify user OK >&2 else echo notify user FAIL >&2 return -1 fi
(良好做法:使用>&2将消息发送给stderr。)
优雅方法2
将通用逻辑转移到共享函数中。
check() {
local command=("$@")
if "${command[@]}"; then
echo notify user OK >&2
else
echo notify user FAIL >&2
exit 1
fi
}
check command1
check command2
check command3优雅方法3
installed () {
command -v "$1" >/dev/null 2>&1
}
if installed
then
xx
else
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
到此这篇关于shell命令返回值判断的方法实现的文章就介绍到这了,更多相关shell命令返回值判断内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
X 关闭
X 关闭
- 15G资费不大降!三大运营商谁提供的5G网速最快?中国信通院给出答案
- 2联想拯救者Y70发布最新预告:售价2970元起 迄今最便宜的骁龙8+旗舰
- 3亚马逊开始大规模推广掌纹支付技术 顾客可使用“挥手付”结账
- 4现代和起亚上半年出口20万辆新能源汽车同比增长30.6%
- 5如何让居民5分钟使用到各种设施?沙特“线性城市”来了
- 6AMD实现连续8个季度的增长 季度营收首次突破60亿美元利润更是翻倍
- 7转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 8充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 9好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 10名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?

