1

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

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.