Skip to content
Advertisement

How to use Linux shell variable with sequence number?

I define several variables like below:

TEMP1=1
TEMP2=1
TEMP3=1

And then I want to use them in a for loop like this, but failed. How to make it work? To use the variable with a sequence number.

for i in 0 1 2 3
do
    if [[ $(TEMP{i}) -eq 1 ]]; then
        do something

Advertisement

Answer

I think you probably need a bash array:

#!/bin/bash

temp=(1 4 9 16)
for i in {0..3}; do
   echo ${temp[i]}
done

Sample Output

1
4
9
16

You should probably avoid uppercase variable names too as they are reserved.

If that is a bit too far from your comfort zone, this may be nearer to your way of thinking but it uses the same underlying technology of bash arrays:

TEMP[0]=1
TEMP[1]=4
TEMP[2]=9

echo ${TEMP[2]}       # echoes "9"
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement