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 ?fi
2.返回錯(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腳本實(shí)現(xiàn)自動(dòng)檢測(cè)修改最快的Ubuntu軟件源
這篇文章主要介紹了Shell腳本實(shí)現(xiàn)自動(dòng)檢測(cè)修改最快的Ubuntu軟件源,本文先是講解了實(shí)現(xiàn)的思路,并給了實(shí)現(xiàn)腳本源碼,需要的朋友可以參考下2014-10-10shell參數(shù)換行與shell輸出換行的方法實(shí)例
這篇文章主要給大家介紹了關(guān)于shell參數(shù)換行與shell輸出換行的方法實(shí)例,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2023-02-02shell腳本編程之case語(yǔ)句學(xué)習(xí)筆記
這篇文章主要介紹了shell腳本編程之case語(yǔ)句學(xué)習(xí)筆記,本文代碼中包含注釋來(lái)說(shuō)明case語(yǔ)句的使用,需要的朋友可以參考下2014-09-09sed或awk處理文件最后一行的實(shí)現(xiàn)方法
sed或awk處理文件最后一行,供大家學(xué)習(xí)參考2013-02-02shell學(xué)習(xí)教程獲取命令行參數(shù)示例
這篇文章主要介紹了shell學(xué)習(xí)中的基礎(chǔ)知識(shí)的獲取命令行參數(shù)示例,需要的朋友可以參考下2014-03-03