How do I assign each line of a variable in BASH into new separate variables (linux newbie)?

I’ve been searching for hours but I can’t find a simple answer on this one.

A variable on a bash script has unknown number of lines. What I want to do is find the simpliest way to assign each line of this variable into new separate variables (without knowing how many these would be) without having to…

To do what you want is fiddly. Really fiddly. Probably involving some sort of loop with eval thrown in the middle. And possibly some nasty file IO redirection. Ugh.

However, bash has arrays and if you don’t mind changing your syntax slightly, will let you do pretty much what you want. This example assumes that each line contains a simple word as per your example. If a line can have spaces it gets harder.


echo ${arr[1]}

The man page for bash does explain this; you’ll need to search for “Arrays”.

Leave a Comment