简体   繁体   English

bash中具有多个条件的for循环

[英]For loop with multiple conditions in bash

first of all, i've read the question for loop with multiple conditions in Bash scripting but it does not work for what i intend to do.首先,我在 Bash 脚本中阅读了具有多个条件的循环问题但它不适用于我打算做的事情。 In the following script, a first for loop assign f quantity of arrays to a pair of variables ( CON_PERC and CON_NAME )在以下脚本中,第一个 for 循环将f个数组分配给一对变量( CON_PERC 和 CON_NAME

f=0
for i in "${container[@]}"; do
CON_PERC[$f]=$(awk '{print int($2+0)}' <<< ="${container[$f]}") #CON_PERC[0] = 2; CON_PERC[1] = 0
CON_NAME[$f]=$(awk '{print $1}' <<< "${container[$f]}") #CON_NAME[0] = hi; CON_NAME[1] = bye
((f++))
done

what i need to do now, is in a separate loop, check every array of both variables and print themm.我现在需要做的是在一个单独的循环中,检查两个变量的每个数组并打印它们。 what would be the best way to do it?最好的方法是什么?

what i tough is something like this我的难处是这样的

e=0
for ((x in "$CON_PERC[@]" && z in "$CON_NAME[@]")); do
echo "${CON_NAME[$e]}  ${CON_PERC[$e]}"
((e++))
done

but it seems that for ((i in "$CON_PERC[@]" && e in "$CON_NAME[@]")) isnt valid in bash.但似乎for ((i in "$CON_PERC[@]" && e in "$CON_NAME[@]"))在 bash 中无效。

The question is, what is the best way to approach this, should i exclusively use a nested loop or is other way around it?问题是,解决这个问题的最佳方法是什么,我应该专门使用嵌套循环还是其他方法?

You need to nest them like this (untested in your examples)您需要像这样嵌套它们(在您的示例中未经测试)

for x in "$CON_PERC[@]";
  do
  for z in "$CON_NAME[@]";
  do
    echo ${CON_NAME[$e]}  ${CON_PERC[$e]}
    ((e++))
  done
done

eg:例如:

for x in {a..b};
do
  for y in {c..d};
  do
    echo $x $y
  done
done

result:结果:

a c
a d
b c
b d

Here you have one way :你有一种方法:

#!/bin/bash


CON_PERC=(1 2 3)
CON_NAME=("Hello" "Hallo" "Hola")

for item in "${CON_PERC[@]}" "${CON_NAME[@]}"
do
    printf "Item : $item\n"
done

This will print :这将打印:

Item : 1
Item : 2
Item : 3
Item : Hello
Item : Hallo
Item : Hola

Hope it helps!希望能帮助到你!

Edit :编辑 :

If you want you want you can use a traditional for loop as well.如果你愿意,你也可以使用传统的 for 循环。 Im assuming both arrays will have the same size :我假设两个数组将具有相同的大小:

#!/bin/bash


CON_PERC=(1 2 3)
CON_NAME=("Hello" "Hallo" "Hola")

for (( i=0 ; i < "${#CON_PERC[@]}"; i++ ))
do
    echo "${CON_PERC[i]} : ${CON_NAME[i]}"
done

You could loop through the array keys of one of your arrays and use this key to get the value:您可以遍历数组之一的数组键并使用此键获取值:

CON_PERC=( 01 02 03 04 )
CON_NAME=( one two three four )

for i in "${!CON_NAME[@]}"; do
  printf '%s %s\n' "${CON_NAME[i]}" "${CON_PERC[i]}"
done

Output:输出:

one 01
two 02
three 03
four 04

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM