shell命令返回值判斷的方法實(shí)現(xiàn)
1.判斷命令是否存在
優(yōu)雅方法1
首先,檢查命令是否有效的慣用方法直接在if語(yǔ)句中。
if command; then ? ? echo notify user OK >&2 else ? ? echo notify user FAIL >&2 ? ? return -1 fi
(良好做法:使用>&2將消息發(fā)送給stderr。)
優(yōu)雅方法2
將通用邏輯轉(zhuǎn)移到共享函數(shù)中。
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優(yōu)雅方法3
installed () {
? ? ? ? command -v "$1" >/dev/null 2>&1
}
if installed <command1>
then
? ? ? ?<command1> ?xx
else
? ? ? ? <command1> ?xxx
?fi2.返回錯(cuò)誤退出
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.返回錯(cuò)誤提示
一般方法:
方法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
優(yōu)雅方法
方法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
到此這篇關(guān)于shell命令返回值判斷的方法實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)shell命令返回值判斷內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Shell腳本如何啟動(dòng)/停止Java的jar程序
這篇文章主要介紹了使用Shell腳本如何啟動(dòng)/停止Java的jar程序,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
Linux定時(shí)執(zhí)行任務(wù)at和crontab命令詳解
本篇文章主要介紹了Linux定時(shí)執(zhí)行任務(wù)at和crontab命令這兩個(gè)命令的基本用法和區(qū)別,一起學(xué)習(xí)下。2017-11-11
shell之創(chuàng)建文件及內(nèi)容的方法示例
這篇文章主要介紹了shell之創(chuàng)建文件及內(nèi)容的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
非常好的12道shell命令經(jīng)典面試問(wèn)題
shell面試題總結(jié)了一些,讓我們一起看一下吧,非常好的12道shell命令經(jīng)典面試問(wèn)題,需要的朋友可以參考下2018-02-02
linux下開(kāi)啟php的sockets擴(kuò)展支持實(shí)例
下面小編就為大家?guī)?lái)一篇linux下開(kāi)啟php的sockets擴(kuò)展支持實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-02-02
Bash腳本實(shí)現(xiàn)實(shí)時(shí)監(jiān)測(cè)登錄
在服務(wù)器的運(yùn)維管理中,及時(shí)監(jiān)控系統(tǒng)的登錄日志對(duì)保障系統(tǒng)的安全至關(guān)重要,下面我們來(lái)看看如何使用Bash腳本實(shí)現(xiàn)實(shí)時(shí)監(jiān)測(cè)登錄日志吧2024-11-11

