0

looking for some help here. I am seeing the below issue

y=1
j$y=`cat /home/devteam/auppu/new_ig_1|head -n $y`
ksh: j1=5555555555555555:  not found

i have no issue when i cat on the file,like below

cat /home/devteam/auppu/new_ig_1|head -n $y
5555555555555555
ady6831983
  • 113
  • 1
  • 8
  • Possible duplicate of [Indirect variable assignment in bash](http://stackoverflow.com/questions/9938649/indirect-variable-assignment-in-bash) – Benjamin W. Jan 10 '16 at 05:21
  • @BenjaminW . so how should i get the o/p without error? – ady6831983 Jan 10 '16 at 05:32
  • @ady6831983 do you need to dynamically name your variable or could it just be j1? – entpnerd Jan 10 '16 at 05:57
  • @JonathanThoms yes, it is in a while loop, so y is incremental. but it will not store the variable because of the above error – ady6831983 Jan 10 '16 at 06:16
  • Do you need to access the variable after the loop is done? Any reason you can't use an array variable? – Benjamin W. Jan 10 '16 at 07:47
  • A while-loop. Do you want the variable j9 filled with the first 9 lines of the file? And j8234 with 8234 lines? What will you do with the vars, awk might help. – Walter A Jan 11 '16 at 22:29

2 Answers2

2

You might have to do something like

y=1
x=j${y}
x=`cat /home/devteam/auppu/new_ig_1|head -n $y`
echo $x

You would need to create an intermediate variable (x in this case) and then assign to it the results of your cat command

vmachan
  • 1,672
  • 1
  • 10
  • 10
2

The simplest way to do this is using an indexed array, like so:

y=1
j[$y]=`cat /home/devteam/auppu/new_ig_1|head -n $y`
echo ${j[$y]}

This way you can store multiple invocations of the cat command in your loop into the associative array referenced by the j variable.

Sam
  • 3,320
  • 1
  • 17
  • 22
  • This is just an indexed array, not an associative one. If you wanted associative, you'd have to declare it as such first. This being said, indexed arrays seem to be the better solution here anyway. – Benjamin W. Jan 10 '16 at 21:56