MST
星途 面试题库

面试题:Bash脚本的复杂测试与并发执行

编写一个Bash脚本,它接收一个目录路径作为参数。脚本需要递归地遍历该目录及其子目录,找到所有的文本文件(可以通过文件扩展名判断,如.txt),并对每个文本文件执行一个外部命令(例如grep命令,用于搜索特定字符串)。要求使用多线程(或多进程)并发执行这些外部命令以提高效率,同时要处理好可能出现的并发冲突和错误,最后将每个文件的处理结果汇总输出。
50.6万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

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

directory=$1
results=()
lockfile=$(mktemp)
max_threads=10
thread_count=0

# 定义处理文件的函数
process_file() {
    local file=$1
    local result=$(grep "特定字符串" $file 2>/dev/null)
    if [ $? -eq 0 ]; then
        # 使用锁来防止并发写入冲突
        flock -x $lockfile
        results+=("$file: $result")
        flock -u $lockfile
    fi
}

# 递归遍历目录
find $directory -type f -name "*.txt" | while read -r file; do
    while [ $thread_count -ge $max_threads ]; do
        # 等待有线程完成
        wait -n
        thread_count=$((thread_count - 1))
    done
    process_file $file &
    thread_count=$((thread_count + 1))
done

# 等待所有线程完成
wait

# 输出结果
echo "处理结果汇总:"
for result in "${results[@]}"; do
    echo $result
done

# 删除临时锁文件
rm $lockfile