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?
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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.