1
List = 1 2 3 4 5
for i in $LIST
do
sum=`expr $l_$i + $b`
done

here l_1, l_2, l_3, l_4 and l_5 are variables having some values. when I am trying to access those values within the for loop using loop variable i, the value of i is getting substituted in the expression i.e the statement (1 + $b) is getting executed instead of ($l_1 + $b). I have tried various combinations of $ symbol and also used paranthesis but nothing seems to be working. Please help!!

  • 2
    List = 1 2 3 4 5 calls the command List with 6 arguments, = being the first of them. – choroba Jun 2 '15 at 11:23
  • 1
    Bash is case sensitive. $List and $LIST are two different variables. – choroba Jun 2 '15 at 11:24
2

Instead of using l_i or list as strings, use arrays:

#! /bin/bash
b=11
l=(12 24 46 68 92)
for i in "${l[@]}" ; do
     ((sum=i+b))
     echo $sum
done
| improve this answer | |
1

You can use two methods if you want to maintain your given example:

  1. using eval: eval expr \${L_$i} + $b
  2. using a reference variable: REF=L_$i; expr ${!REF} + $b;

As choroba mentioned bash is case sensitive so please be careful with your variable names.

| improve this answer | |
  • I added the script because I felt it would be more helpful, but your answer is pretty thorough. – Grasshopper Jun 2 '15 at 12:30
  • There is another option. Reference variables aren't even an option in many shells. Simple POSIX arithmetic substitution will evaluate all expansions in an expression before doing any math - that's the specified behavior. And so if x=v v=20 i=$((10+$x)) is run, $i will equal 30. There's an answer here which demonstrates this given the example code. And your eval, by the way, is dangerous. Not because eval is evil or any of that nonsense - it's because you're not protecting the order of expansion. – mikeserv Jun 2 '15 at 19:46
0
l_1=10 l_2=20 l_3=30 l_4=40 l_5=50
b=100
for i  in    1 2 3 4 5
do     echo "$((sum=l_$i+b))"
done

The value of $sum is set above in the current shell - it can be expanded or modified in the normal way. This occurs without the subshell/pipe overhead necessary for invoking/forking expr and its parent shell for each iteration.

OUTPUT:

110
120
130
140
150

Or, if you really want to use expr:

for i  in  1 2 3 4 5
do     sum=`expr "$((l_$i))" + "$b"`
       echo "$sum"
done

OUTPUT:

110
120
130
140
150
| improve this answer | |
0

I'm no bash expert but here's what I came up with

#!/bin/bash
 b=1
 l_1=1
 l_2=2
 l_3=3
 for i in '$l_'{1,2,3}
 do
   eval dvar="${i}"
   sum=$(($dvar + $b))
 done

The i variable of the for loop will be initialized as '$l_1', '$l_2', and so on. Calling eval will then evaluate the value of i into dvar which then can be used in an arithmetic expression.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.