0

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. In the following script, a first for loop assign f quantity of arrays to a pair of variables (CON_PERC and 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.

The question is, what is the best way to approach this, should i exclusively use a nested loop or is other way around it?

3 Answers 3

3

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. 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
Sign up to request clarification or add additional context in comments.

1 Comment

hey thanks, the second way is exactly what i wanted to do
1

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

e.g.:

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

2 Comments

so there's no other way than nested to do it?
Not as far as I'm aware - no edit: this seems like it might work: stackoverflow.com/questions/22840498/… where by you combine x and z as a single thing and iterate over that instead.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.