0

sh version : 1.14.7

#!/bin/sh
cpu_to_eth1=10
cpu_to_eth2=20
cpu_to_eth3=30
cpu_to_eth4=40
i=0
for i in 1 2 3 4
do
 echo "value of the $i th varible is $cpu_to_eth$i"
done

it is not working properly,the output should be

value of the 1 th varible is 10
value of the 2 th varible is 20
value of the 3 th varible is 30
value of the 4 th varible is 40
2
  • that's $cpu_to_eth, followed by $i. just as you would expect. Commented Sep 16, 2013 at 10:17
  • What are you using that you are stuck on a 20+ year old version of bash? Commented Sep 16, 2013 at 18:34

3 Answers 3

1

Without requiring bash:

#!/bin/sh
cpu_to_eth1=10
cpu_to_eth2=20
cpu_to_eth3=30
cpu_to_eth4=40
for i in 1 2 3 4; do
  eval echo "value of the $i th varible is "$"cpu_to_eth$i"
done

This should work in any POSIX shell (e.g. in dash, the default shell in Ubuntu).

The point is that you need two evaluations (for an indirect evaluation):

  1. evaluate $i to get the name of the variable (cpu_to_eth$i)
  2. evaluate the variable cpu_to_eth$i to get its actual value

The second-order evaluation needs a separate eval (or a bash-ism)

Sign up to request clarification or add additional context in comments.

2 Comments

val=eval echo ""$"cpu_to_eth$i" i want to store the whole value in another variable, but it is not working
You didn't ask for that. eval another_var=\$"cpu_to_eth$i"
1

With bash, it's more appropriate to use an array here, rather than have multiple variables.

Example of an array:

cpu_to_eth_arr=( 10 20 30 40 )
for i in "${cpu_to_eth_arr[@]}"
do
    echo "$i"
done

Another way, using an associative array:

cpu_to_eth[1]=10
cpu_to_eth[2]=20
cpu_to_eth[3]=30
cpu_to_eth[4]=40

for i in "${!cpu_to_eth[@]}"
do
    echo "value of the $i th varible is ${cpu_to_eth[$i]}"
done

1 Comment

I do not have array support in my bash version
0

Using bash you can perform the Shell parameter expansion:

#!/bin/bash

cpu_to_eth1=10
cpu_to_eth2=20
cpu_to_eth3=30
cpu_to_eth4=40

i=0

for i in 1 2 3 4
do
 val=cpu_to_eth${i} # prepare the variable
 echo value of the $i th varible is ${!val} # expand it
done

3 Comments

test.sh: ${!val}: bad substitution
Note that I also changed the first line: from #!/bin/sh to #!/bin/bash.
ya but my bash version is too old

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.