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