0

I have a text file with several lines and would like to write a bash script that reads the text file and store each line in different variable.

Here is how my file looks like.

cat file.txt

 line1
 line2
 line3

I would like to get the following:

variable1=line1
variable2=line2
variable3=line3

Do you have any idea how can I do this?

4
  • 2
    Use readarray (also known as mapfile) to read each line into an array. Then you can reference each line at the indexes 0 - n-1. Commented Jan 17, 2019 at 2:54
  • what happens next will probably dictate the best solution. Commented Jan 17, 2019 at 2:58
  • True, but without knowing the number of lines before-hand, it would be impossible to read each line into an independently named variable without some type of nameref scheme. Commented Jan 17, 2019 at 3:01
  • 1
    Put each line into an array and then reference them by index is probably a better idea, please see this answer stackoverflow.com/a/30988704/10340970 Commented Jan 17, 2019 at 3:01

1 Answer 1

2

This question is unique in a sense it does not duplicate into any of this, this or this. So answering the question henceforth.

You might need a loop that runs through the file and set variables on-the-fly as below.

n=1
while IFS= read -r "variable$n"; do
  n=$((n + 1))
done < file.txt

and print the variables to see the content retrieved

for ((i=1; i<n; i++)); do 
    var="variable$i"
    printf '%s\n' "${!var}"
done
Sign up to request clarification or add additional context in comments.

Comments

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.