MST
星途 面试题库

面试题:Bash复杂目录遍历与权限调整及错误处理

编写一个Bash脚本,要求在遍历一个复杂嵌套目录结构时,对于所有普通文件,如果其所属用户为当前用户,并且文件权限不是644,则将其权限修改为644。在遍历过程中,需要正确处理各种可能出现的错误,如权限不足、目录不存在等情况,并将错误信息记录到一个指定的日志文件中。同时,脚本要能够处理软链接,确保软链接指向的目标文件也能正确检查和处理权限。
27.7万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

log_file="error_log.txt"
current_user=$(whoami)

# 遍历目录函数
traverse_dir() {
    local dir=$1
    if [ ! -d "$dir" ]; then
        echo "$(date): Directory $dir does not exist" >> "$log_file"
        return
    fi

    for item in "$dir"/*; do
        if [ -L "$item" ]; then
            # 处理软链接,获取链接目标并处理
            target=$(readlink "$item")
            if [ -f "$target" ]; then
                file_user=$(stat -c "%U" "$target")
                file_perm=$(stat -c "%a" "$target")
                if [ "$file_user" = "$current_user" ] && [ "$file_perm" != "644" ]; then
                    if chmod 644 "$target"; then
                        echo "$(date): Changed permissions of $target to 644"
                    else
                        echo "$(date): Permission change failed for $target" >> "$log_file"
                    fi
                fi
            else
                echo "$(date): Soft link $item points to non - existent file" >> "$log_file"
            fi
        elif [ -d "$item" ]; then
            traverse_dir "$item"
        elif [ -f "$item" ]; then
            file_user=$(stat -c "%U" "$item")
            file_perm=$(stat -c "%a" "$item")
            if [ "$file_user" = "$current_user" ] && [ "$file_perm" != "644" ]; then
                if chmod 644 "$item"; then
                    echo "$(date): Changed permissions of $item to 644"
                else
                    echo "$(date): Permission change failed for $item" >> "$log_file"
                fi
            fi
        else
            echo "$(date): Unknown file type for $item" >> "$log_file"
        fi
    done
}

# 开始遍历根目录,可修改为需要遍历的起始目录
traverse_dir "/"