0

I am using the for loop to print the below variables using the below statement but its not printing the values correctly. Its giving only the iteration value. Can someone help me?

value1="1500067"
value2="1500068"
value3="1500069"
package1="CNN"
package2="FOX"
package3="Discovery"

for iteration in {1..3}
do
echo ""$value""$iteration" - "$package""$iteration""
done

Expected Output:

1500067 - CNN
1500068 - Fox
1500069 - Discovery

2 Answers 2

3

You should really use arrays for this kind of task:

#!/bin/bash
values=( 
    1500067
    1500068
    1500069
)
packages=( 
    CNN 
    FOX 
    Discovery
)

for (( i=0; i < ${#values[@]}; i++ )); do
    echo "${values[i]} - ${packages[i]}"
done

Or, since you have natural key-value pairs, an associative array

#!/bin/bash
declare -A packages=( 
    [1500067]=CNN 
    [1500068]=FOX 
    [1500069]=Discovery
)

for key in "${!packages[@]}"; do
    echo "$key - ${packages[$key]}"
done
2

I was able to accomplish this using the following:

#!/bin/sh
value1="1500067"
value2="1500068"
value3="1500069"
package1="CNN"
package2="FOX"
package3="Discovery"

for i in {1..3}; do
    var1="value$i"
    var2="package$i"
    echo "${!var1} - ${!var2}"
done

Your double quoting of the echo command is overkill, you have actually unquoted the variables because of the way it was setup. Simply wrapping the entire argument in a single pair of quotes is fine. If you run into a situation where you need to butt something up against your variable it's better to use brackets to preserve it's name:

${var1}_something_else

Be aware though that despite the #!/bin/sh hashbang, I believe this contains some bash-isms {1..3} and the indirect references ${1var}. It works on my system though.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .