shell命令返回值判斷的方法實現(xiàn)
更新時間:2022年02月24日 11:41:42 作者:ghostwritten
本文主要介紹了shell命令返回值判斷的方法實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
1.判斷命令是否存在
優(yōu)雅方法1
首先,檢查命令是否有效的慣用方法直接在if語句中。
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.返回錯誤退出
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
優(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命令返回值判斷的方法實現(xiàn)的文章就介紹到這了,更多相關(guān)shell命令返回值判斷內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Shell腳本實現(xiàn)自動檢測修改最快的Ubuntu軟件源
這篇文章主要介紹了Shell腳本實現(xiàn)自動檢測修改最快的Ubuntu軟件源,本文先是講解了實現(xiàn)的思路,并給了實現(xiàn)腳本源碼,需要的朋友可以參考下2014-10-10shell學(xué)習(xí)教程獲取命令行參數(shù)示例
這篇文章主要介紹了shell學(xué)習(xí)中的基礎(chǔ)知識的獲取命令行參數(shù)示例,需要的朋友可以參考下2014-03-03