首页 > 解决方案 > 如何在bash的for循环中迭代2个数组

问题描述

我正在编写一个脚本,该脚本应根据环境的使用类型和发布日期在环境中安装修补程序。为此,我需要检查环境类型以及修补程序的发布日期。如果环境的使用类型是prodtime1自发布修补程序以来经过的秒数,则安装修补程序。

通过阅读网站上的类似问题,我想出了这个。

u=( prod test dev)
t=( time2 time2 time3 )

# where t represents the number of seconds that must pass after the release date in order for the hotfix to be installed

for ((i=0;i<${#u[@]};i++))
do
    if ($usage_type=${u[i]} && $hf_release_date -ge $current_time+${t[i]}); then install_hotfix; fi 
done

上面的代码会按预期工作吗?

编辑:

我尝试修复语法,但我仍然缺少一些东西:

u=( prod test dev)
t=( time2 time2 time3 )

# where t represents the number of seconds that must pass after the release date in order for the hotfix to be installed

for ((i=0;i<${#u[@]};i++))
do
    if [[ "$usage_type" == "${u[i]}" ]] && [[ "$hf_release_date" -ge "$current_time"+"${t[i]}" ]]; then install_hotfix; fi 
done

标签: arrayslinuxbashshellfor-loop

解决方案


如果您的问题是“如何遍历两个数组”,您可以通过运行下一个片段来检查您的代码部分是否正确:

u=( prod test dev)
t=( time2 time2 time3 )

for ((i=0;i<${#u[@]};i++)) 
  do echo "u[$i] = ${u[i]}, t[$i] = ${t[i]}"
done

输出:

u[0] = prod, t[0] = time2
u[1] = test, t[1] = time2
u[2] = dev, t[2] = time3

推荐阅读