MST

星途 面试题库

面试题:复杂场景下Bash脚本参数传递与处理及异常处理

编写一个Bash脚本用于管理数据库备份任务。脚本接收以下参数:备份类型(full或incremental)、数据库名称、目标存储路径。如果备份类型为full,需要进行完整备份操作,若为incremental则进行增量备份操作。在备份过程中,可能会因为权限不足、磁盘空间不足等问题导致备份失败。请实现这个脚本,并对可能出现的错误进行合理的异常处理,将错误信息记录到指定的日志文件中,同时通过合适的方式通知系统管理员备份任务的执行结果(例如发送邮件,假设邮件发送命令为`sendmail -s "Backup Result" admin@example.com`)。
45.2万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

# 检查参数个数
if [ $# -ne 3 ]; then
    echo "Usage: $0 backup_type database_name target_path"
    exit 1
fi

backup_type=$1
database_name=$2
target_path=$3
log_file="backup_log.txt"
error_occurred=false

# 检查备份类型
if [ "$backup_type" != "full" ] && [ "$backup_type" != "incremental" ]; then
    echo "Invalid backup type. Allowed values are 'full' or 'incremental'" | tee -a $log_file
    error_occurred=true
fi

# 执行备份操作
if [ "$backup_type" = "full" ]; then
    echo "Performing full backup of $database_name to $target_path" | tee -a $log_file
    # 这里用模拟命令替代实际备份命令,例如 mysqldump 等
    tar -czvf $target_path/$database_name-full-$(date +%Y%m%d%H%M%S).tar.gz /path/to/$database_name 2>>$log_file
    if [ $? -ne 0 ]; then
        echo "Full backup failed" | tee -a $log_file
        error_occurred=true
    else
        echo "Full backup succeeded" | tee -a $log_file
    fi
elif [ "$backup_type" = "incremental" ]; then
    echo "Performing incremental backup of $database_name to $target_path" | tee -a $log_file
    # 这里用模拟命令替代实际备份命令,例如 rsync 等
    rsync -avz --backup --suffix=.bak /path/to/$database_name $target_path 2>>$log_file
    if [ $? -ne 0 ]; then
        echo "Incremental backup failed" | tee -a $log_file
        error_occurred=true
    else
        echo "Incremental backup succeeded" | tee -a $log_file
    fi
fi

# 通知系统管理员备份结果
if $error_occurred; then
    echo "Backup failed. Check $log_file for details." | sendmail -s "Backup Result" admin@example.com
else
    echo "Backup succeeded." | sendmail -s "Backup Result" admin@example.com
fi