Ing Dedek
Ing Dedek

Reputation: 173

How can I fill the variables from file?

How can I fill the variables from file?

In /root/file I have 4 lines (number and text)

478
144
text
0

How can I set the values of four variables, one value from each line of the file?

The desired result:

ABC="478"
DEF="144"
GHI="text"
JKL="0"

Upvotes: 2

Views: 207

Answers (1)

chepner
chepner

Reputation: 531265

Say the file is called file.txt. Just read each line into the desired variable, one at a time, using a compound command.

{ IFS= read -r ABC; IFS= read -r DEF; IFS= read -r GHI; IFS= read -r JKL; } < file.txt

If you know that file.txt is "simple", that is, you don't care about leading or trailing whitespace on the lines or backslash-escaped line continuations, you can drop the IFS= and -r clutter and just use

{ read ABC; read DEF; read GHI; read JKL; } < file.txt

We use the compound command { ... } to share the input from file.txt among all the reads; without it, using something like

read ABC < file.txt
read DEF < file.txt
read GHI < file.txt
read JKL < file.txt

each read would read from the beginning of the file, resulting in the first line of the file being assigned four times.

Upvotes: 4

Related Questions