日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

shell命令返回值判斷的方法實現_linux shell

作者:ghostwritten ? 更新時間: 2022-04-28 編程語言

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

原文鏈接:https://blog.csdn.net/xixihahalelehehe/article/details/104819343

欄目分類
最近更新