面试题答案
一键面试#!/bin/bash
# 日志文件路径
log_file="file_type_detection.log"
# 检测文件类型的函数
detect_file_type() {
local file_path="$1"
local file_type
file_type=$(file -b "$file_path" 2>/dev/null)
if [ $? -ne 0 ]; then
echo "Error: Unable to determine file type for $file_path" | tee -a $log_file
return
fi
echo "$file_path: $file_type" | tee -a $log_file
}
# 遍历共享文件存储目录
for file in /path/to/shared/files/*; do
if [ -f "$file" ]; then
detect_file_type "$file"
elif [ -d "$file" ]; then
for sub_file in "$file"/*; do
if [ -f "$sub_file" ]; then
detect_file_type "$sub_file"
fi
done
else
echo "Warning: Skipping non - file or non - directory entry: $file" | tee -a $log_file
fi
done
说明:
- 日志文件:脚本会将文件类型检测结果以及错误信息记录到
file_type_detection.log
文件中。 - 检测函数:
detect_file_type
函数使用file -b
命令来获取文件类型,-b
选项使得输出不包含文件名。如果获取文件类型失败,记录错误信息到日志。 - 遍历目录:外层循环遍历共享文件存储目录,对于文件直接检测类型;对于目录,再遍历其内部文件进行检测。如果遇到既不是文件也不是目录的条目,记录警告信息并跳过。
为了优化性能,在大规模文件检测场景下,可以考虑以下几点:
- 并行处理:使用
xargs
结合parallel
工具,将文件分批次并行检测,加快整体检测速度。 - 缓存机制:对于已经检测过的文件类型或者文件系统特征,可以建立缓存,避免重复检测。