Reputation: 2614
This is different from other questions such as Bash read from file and store to variables as I don't want to loop over the content for all possible lines.
To limit overhead, I'm calling read
twice instead of piping something like head -n2
. But to make read
work like this, I'm redirecting it to a for loop.
This feels dirty as I'm using a loop from {1..1}
and assigning to variable i
which is never used. But this has been the simplest approach that I've found.
Is there any way to further minimize this approach to reading variables from a file while keeping overhead low? The best answer uses only bash built-ins and is both as clean and fast as possible.
File to read:
123
456
789
Script:
for i in {1..1}; do
read -r a
read -r b
done < file
echo $a
echo $b
Output:
123
456
Upvotes: 1
Views: 47
Reputation: 241811
I'd do it with a simple {
… }
block:
{ read -r a; read -r b; } < file
Upvotes: 1