Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash read from file and store to variables in MATLAB

Tags:

bash

matlab

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!

like image 562
user3654549 Avatar asked Dec 12 '22 00:12

user3654549


2 Answers

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

like image 99
dvhh Avatar answered Dec 22 '22 17:12

dvhh


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.

like image 25
mklement0 Avatar answered Dec 22 '22 17:12

mklement0