MST
星途 面试题库

面试题:Bash批量处理特定目录下文件

假设有一个目录/data,其中包含多种类型的文件,现在要求你编写一个Bash脚本,将/data目录下所有后缀名为.log的文件移动到/data/logs子目录中。如果/data/logs目录不存在,则先创建它。同时,将移动成功的文件名记录到/data/moved_logs.txt文件中,若移动过程中出现错误,将错误信息记录到/data/error_logs.txt文件中。
35.8万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

# 检查并创建 /data/logs 目录
if [ ! -d "/data/logs" ]; then
    mkdir /data/logs
fi

# 移动.log文件并记录结果
for file in /data/*.log; do
    if [ -f "$file" ]; then
        mv "$file" /data/logs 2>/data/error_logs.txt
        if [ $? -eq 0 ]; then
            echo "$file" >> /data/moved_logs.txt
        fi
    fi
done