I'm trying to read 2 floating numbers from a very simple 1-line file in Bash. I want to store these two numbers into variables. All the examples I see from Googling look like:
while read VAR1 VAR2
do
<command>
done < file.txt
But this keeps VAR1
and VAR2
inside the while
loop only. How can I store the two variables so that I can use them anywhere in my script? Thanks so much!
The while
loop is superfluous when reading a file with a single line (as described in your question ).
why not simply do :
read VAR1 VAR2 < file.txt
echo $VAR1
echo $VAR2
This would read the first line of your file
dvhh's answer contains the crucial pointer:
If you're reading only a single line, there's no reason to use a while
loop at all.
Your while
loop leaves $VAR1
and $VAR2
empty, because the last attempt to read
from the input file invariably fails due to having reached EOF, causing the variables to be set to the empty string.
If, by contrast, you truly needed to read values from multiple lines and needed to access them after the loop, you could use a bash array:
aVar1=() aVar2=() # initialize arrays
while read var1 var2
do
aVar1+=( "$var1")
aVar2+=( "$var2")
done < file.txt
# ${aVar1[@]} now contains all $var1 values,
# ${aVar2[@]} now contains all $var2 values.
Note that it's good practice not to use all-uppercase names for shell variables so as to avoid conflicts with environment variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With