Search code examples
bashlinegit-bash

bash: How to properly read/assign multiple lines to variables from text file


I apologize if this is a duplicate but I have not found a good answer yet. I have a text file that contains three paths, each as a new line:

path1
path2
path3

I want to assign these paths to three variables. When I read in the text file and assign these three paths to three variables, the first variable gets correctly assigned to path1 but not the second/third, and the first variable gets re-assigned to the path2. Both second/third variables are always empty (possibly line breaks?)

while read -r a b c; do
    echo first_path is $a
    echo second_path is $b
    echo third_path is $c
done < ./ready.txt

the output is

first_path is path1
second_path is
third_path is
first_path is path2
second_path is
third_path is

It must be a simple mistake. Any help is appreciated. Thank you.


Solution

  • Each call to read reads a single line. What you want to iterate over is the names of the variables.

    for name in first_path second_path third_path; do
      read -r "$name"
      echo "$name is ${!name}"
    done