Linux异常处理

By | 2021年12月31日

1 set -e 命令

正常情况下,我们会在sh脚本开头写上set -e,这是为了让语句报错时,可以立即退出shell,而不是继续执行下一条语句。

2 设陷阱(trap)

使用 set -e 无法捕获是哪一行的命令报错的,这里我们改用trap更好,它不仅具有 set -e的功能,还可以自定义输出执行错误的命令和行号:

#!/bin/bash
f () {
    errcode=$? # save the exit code as the first thing done in the trap function
    echo "--------------------------------"
    echo "error $errorcode"
    echo "the command executing at the time of the error was"
    echo "$BASH_COMMAND"
    echo "on line ${BASH_LINENO[0]}"
    echo "--------------------------------"
    # do some error handling, cleanup, logging, notification
    # $BASH_COMMAND contains the command that was being executed at the time of the trap
    # ${BASH_LINENO[0]} contains the line number in the script of that command
    # exit the script or return to try again, etc.
    exit $errcode  # or use some other value or do return instead
}
trap f ERR

ls | grep abcd  #这里查询不到 abcd 就直接退出
#false #或者直接输入false,也会触发trap

3 grep 找不到会抛异常

上面脚本已经提到,当执行 “ls | grep abcd”  时,如果找不到字符串“abcd”,就会报错。如果你设置了 “set -e”或“trap”,就会直接退出,不再向下执行命令。

有时候,我们并不想因为 grep找不到字符串而直接退出,这时可以再grep后面添加 | { grep -v grep || true; }来解决:

SHA_FILE=`cat image/falsolr.${FAL_VERSION}.sha | awk '{print substr($1,8,12)}'`
IMAGE_GREP=`docker image ls | grep ${SHA_FILE} | { grep -v grep || true; }`
if [ -z "$IMAGE_GREP" ]
then
    docker load -i ${SOLR_IMAGE}
fi

发表评论

您的电子邮箱地址不会被公开。