Aaron
Aaron

Reputation: 3325

Increase variable count using i++ in shell script

Code:

website="https://www.test.com/"
item_1="stuff"
item_2="more-stuff"

        while [1]
        do {
            for (i=1; $i<=3; i++)
              do {
                  echo $website$item_$i &
                  sleep 2
                 }
                 done
           }
           done

Output I'm getting:

https://www.test.com/1
https://www.test.com/2

Output I desire:

https://www.test.com/stuff
https://www.test.com/more-stuff

I am trying to increment the "item" variables by using $i in place of the number, so I may loop through them, but it is not giving me the desired results. Is there a way to make this possible?

Upvotes: 0

Views: 2099

Answers (2)

MauricioRobayo
MauricioRobayo

Reputation: 2356

Using item_x variables and inderect variable references:

#!/bin/bash

website="https://www.test.com/"
item_1="stuff"
item_2="more-stuff"

while true; do
    for (( i=1; i<=3; i++)); do
       item=item_$i
       echo $website${!item}
       sleep 2
    done
done

To create the indirect variable reference, first we have to create a variable that stores the name of the variable we want to indirectly reference, hence:

item=item_$i
# item stores the name of the variable we want  to 
# indirectly reference, be it item_1, item_2, etc.

Now that we have the name of the variable we want to reference in another variable, we use inderect reference to retrieve not the value of the variable item, but the value of the variable that is stored inside that variable, that is item_x:

${!item}

So var item stores the name of the variable we want to indirectly referenced by using the ${!var} notation.

It can be much simpler if you use an array instead:

#!/bin/bash

website=https://www.test.com/
items=( stuff more-stuff )

# You can refer to each item on the array like this:
echo ${items[0]}
echo ${items[1]}

while true; do
    for item in "${items[@]}"; do 
        echo "$website$item"
        sleep 2
    done
done

Also can try this other way:

#!/bin/bash

website="https://www.test.com/"
item[1]="stuff"
item[2]="more-stuff"

while true; do
   for (( i=1; i<=3; i++)); do
       echo $website${item[i]}
       sleep 2
   done
done

Upvotes: 3

sheplu
sheplu

Reputation: 2975

You can use what we call indirect parameter expension ${!B} Two others threads are speaking about it.

How to get a variable value if variable name is stored as string?

Dynamic variable names in Bash

Upvotes: 0

Related Questions