Skip to content

错误处理

退出状态

查看退出状态

bash
#!/bin/bash

# 执行命令
command

# 查看退出状态
echo $?

退出状态值

bash
#!/bin/bash

# 0: 成功
# 1-255: 失败

# 检查退出状态
if [ $? -eq 0 ]; then
    echo "命令执行成功"
else
    echo "命令执行失败"
fi

错误处理

基本错误处理

bash
#!/bin/bash

# 执行命令并检查退出状态
command
if [ $? -ne 0 ]; then
    echo "命令执行失败"
    exit 1
fi

使用 && 和 ||

bash
#!/bin/bash

# 使用 && 连接命令
command1 && command2

# 使用 || 连接命令
command1 || command2

# 组合使用
command1 && command2 || echo "命令执行失败"

trap 命令

捕获信号

bash
#!/bin/bash

# 捕获信号
trap 'echo "捕获信号"' SIGINT SIGTERM

# 脚本内容
while true; do
    echo "运行中..."
    sleep 1
done

清理资源

bash
#!/bin/bash

# 定义清理函数
cleanup() {
    echo "清理资源..."
    rm -f /tmp/tempfile
}

# 捕获退出信号
trap cleanup EXIT

# 创建临时文件
touch /tmp/tempfile

# 脚本内容
echo "脚本执行中..."

实用示例

示例1:错误处理

bash
#!/bin/bash

# 定义错误处理函数
error_exit() {
    echo "错误: $1" >&2
    exit 1
}

# 执行命令并检查退出状态
command || error_exit "命令执行失败"

示例2:重试机制

bash
#!/bin/bash

# 定义重试函数
retry() {
    local max_attempts=$1
    shift
    local command=("$@")
    local attempt=1

    while [ $attempt -le $max_attempts ]; do
        echo "尝试 $attempt/$max_attempts: ${command[@]}"
        "${command[@]}"
        if [ $? -eq 0 ]; then
            echo "命令执行成功"
            return 0
        fi
        attempt=$((attempt + 1))
        sleep 1
    done

    echo "命令执行失败"
    return 1
}

# 使用重试函数
retry 3 command

示例3:日志记录

bash
#!/bin/bash

# 定义日志函数
log() {
    local level="$1"
    local message="$2"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] [$level] $message" >&2
}

# 定义错误处理函数
error_exit() {
    log "ERROR" "$1"
    exit 1
}

# 使用日志函数
log "INFO" "程序启动"
command || error_exit "命令执行失败"
log "INFO" "程序完成"

示例4:资源清理

bash
#!/bin/bash

# 定义清理函数
cleanup() {
    log "INFO" "清理资源..."
    rm -f /tmp/tempfile
    log "INFO" "资源清理完成"
}

# 捕获退出信号
trap cleanup EXIT

# 创建临时文件
touch /tmp/tempfile

# 脚本内容
log "INFO" "脚本执行中..."

最佳实践

1. 检查退出状态

bash
# 好的做法
command
if [ $? -ne 0 ]; then
    echo "命令执行失败"
    exit 1
fi

# 不好的做法
command

2. 使用 trap

bash
# 好的做法
trap cleanup EXIT

# 不好的做法
cleanup

3. 使用日志

bash
# 好的做法
log "ERROR" "命令执行失败"

# 不好的做法
echo "命令执行失败"

总结

错误处理的关键点:

  1. 退出状态:查看和检查退出状态
  2. 错误处理:基本错误处理、使用 &&||
  3. trap 命令:捕获信号、清理资源
  4. 实用示例:错误处理、重试机制、日志记录、资源清理
  5. 最佳实践:检查退出状态、使用 trap、使用日志

恭喜你!你已经完成了 Shell 脚本教程的学习。继续练习和实践,你将掌握 Shell 脚本编程的精髓。