MST

星途 面试题库

面试题:Bash脚本中批量处理文件权限与所有权

编写一个Bash脚本,实现对指定目录下(包括子目录)所有文件的权限设置为`644`,并将其所有权设置为`admin`用户和`admin_group`组。同时要处理可能出现的权限不足等错误情况。
22.7万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

# 检查参数个数
if [ $# -ne 1 ]; then
    echo "Usage: $0 <directory_path>"
    exit 1
fi

directory=$1

# 检查目录是否存在
if [ ! -d "$directory" ]; then
    echo "Directory $directory does not exist."
    exit 1
fi

# 尝试更改文件权限和所有权
find "$directory" -type f -exec chmod 644 {} \; 2>&1 | tee -a chmod_errors.log
find "$directory" -type f -exec chown admin:admin_group {} \; 2>&1 | tee -a chown_errors.log

# 检查错误日志文件
if [ -s chmod_errors.log ] || [ -s chown_errors.log ]; then
    echo "There were errors during chmod or chown operations. Check the error logs:"
    echo "Chmod errors: chmod_errors.log"
    echo "Chown errors: chown_errors.log"
else
    echo "Permissions and ownership set successfully for all files in $directory."
fi

# 删除错误日志文件
rm -f chmod_errors.log chown_errors.log