rmaan
rmaan

Reputation: 85

print a variable using another

I have my script setup like this, i want to print switch names using loop.

swn1="something"
swn2="somethingelse"

for (( i=1; i<="$ii"; i++ ))
    do              
       echo "$swn$i "
    done

I have searched and searched but no luck, can anyone help me how to print swn using for loop ?

Upvotes: 1

Views: 71

Answers (3)

konsolebox
konsolebox

Reputation: 75618

The solution for that is variable indirection.

swn1="something"
swn2="somethingelse"

for (( i=1; i<="$ii"; i++ ))
    do              
        var="swn$i"
        echo "${!var}"
    done

Although normally you could solve your problem with arrays, but the way to print a variable using another is through it.

As explained in the bash manual:

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix} and ${!name[@]}. The exclamation point must immediately follow the left brace in order to introduce indirection.

Upvotes: 2

ben_re
ben_re

Reputation: 528

Sounds like you want an array...

swn=("something" "something else")

for i in "${swn[@]}"
do
    echo $i
done

Upvotes: 3

Phil H
Phil H

Reputation: 20151

You can't do this. swn1 is one token, swn2 is another. It looks like you want an array, and if you want an array in a bash script you either want to process the values as separate lines in a file, or switch to using Perl.

Separate lines:

echo "something" > swnfile;
echo "somethingelse" >> swnfile;
cat file | while read line; do
    echo "$line";
done

Upvotes: 0

Related Questions