MST
星途 面试题库

面试题:Bash脚本中如何实现简单的文件备份并记录操作日志

请编写一个Bash脚本,实现将指定目录下的所有文件备份到另一个目录,并在备份过程中记录每次备份操作的时间、源文件路径和目标文件路径到一个日志文件中。
30.0万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

source_dir=$1
target_dir=$2
log_file="backup_log.txt"

if [ -z "$source_dir" ] || [ -z "$target_dir" ]; then
    echo "Usage: $0 <source_directory> <target_directory>"
    exit 1
fi

if [ ! -d "$source_dir" ]; then
    echo "Source directory $source_dir does not exist."
    exit 1
fi

if [ ! -d "$target_dir" ]; then
    mkdir -p "$target_dir"
fi

for file in "$source_dir"/*; do
    if [ -f "$file" ]; then
        file_name=$(basename "$file")
        target_file="$target_dir/$file_name"
        cp "$file" "$target_file"
        backup_time=$(date +"%Y-%m-%d %H:%M:%S")
        echo "$backup_time $file $target_file" >> "$log_file"
    fi
done