You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash脚本中如何实现两组目录与对应源目录的关联循环?

解决Bash中目录与对应源目录的关联遍历问题

要避免嵌套循环产生的笛卡尔积,核心是让源目录和对应的目标目录组一一绑定,而非交叉遍历。以下是两种可靠的实现方式:

方法1:索引数组配对(简洁直观)

将每组的源目录和目标目录列表分别存入两个索引数组,通过索引同步遍历,确保每组的源与目标对应:

# 定义配对数组:src_dirs存源目录,target_groups存对应目标目录(空格分隔)
src_dirs=("/src" "/src2")
target_groups=("/dir1 /dir2" "/dir3 /dir4")

# 遍历数组索引,同步获取对应源目录和目标目录组
for idx in "${!src_dirs[@]}"; do
    current_src="${src_dirs[$idx]}"
    current_targets="${target_groups[$idx]}"

    # 遍历当前组的每个目标目录
    for dir in $current_targets; do
        # 查找源目录下最新的.mux文件(用find避免文件名空格/排序问题)
        latest_mux=$(find "$current_src" -maxdepth 1 -type f -name "*.mux" -printf "%T@ %p\n" | sort -nr | awk '{print $2}' | head -n1)
        
        if [[ -n "$latest_mux" ]]; then
            echo "处理: 源目录 $current_src 的最新文件 $latest_mux -> 目标目录 $dir"
            # 这里添加你的业务逻辑,例如 cp "$latest_mux" "$dir/"
        else
            echo "警告: 源目录 $current_src 下无.mux文件"
        fi
    done
done

方法2:关联数组(适合带标识的多组场景)

如果需要给每组命名(方便维护),可以用关联数组绑定组名与对应的源/目标目录:

# 声明关联数组
declare -A src_map
declare -A target_map

# 配置各组的源目录和目标目录
src_map["video_group"]="/src"
target_map["video_group"]="/dir1 /dir2"

src_map["audio_group"]="/src2"
target_map["audio_group"]="/dir3 /dir4"

# 遍历所有组名,同步获取对应源和目标
for group in "${!src_map[@]}"; do
    current_src="${src_map[$group]}"
    current_targets="${target_map[$group]}"

    for dir in $current_targets; do
        latest_mux=$(find "$current_src" -maxdepth 1 -type f -name "*.mux" -printf "%T@ %p\n" | sort -nr | awk '{print $2}' | head -n1)
        
        if [[ -n "$latest_mux" ]]; then
            echo "[$group] 处理: $latest_mux -> $dir"
            # 业务逻辑代码
        fi
    done
done

关键注意事项

  • 放弃嵌套遍历所有源目录和目标目录的写法,那必然会产生笛卡尔积。
  • 用find替代ls -t查找最新文件:ls对含空格的文件名处理容易出错,且排序结果可能受系统locale影响,find结合时间戳排序更稳定可靠。

内容的提问来源于stack exchange,提问作者Red_badger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 22:25:27