1

I want to read a file with the data ordered in column.
In the script that I'm writing I use the read command.

The input file is made by lines like the following:

XX:XX:XX:XX:XX   PQRTS
YY:YY:YY:YY:YY   ABCDE
ZZ:ZZ:ZZ:ZZ:ZZ   FGHIJ

What I'm using to read it is something like this

while read a b; do 
echo $a
echo $b
done < filename.txt

Till now it reads line by line and assigns XX:XX:XX:XX:XX to a and PQRTS to b in first iteration of the while cycle, after YY:YY:YY:YY:YY to a and ABCDE to b in the second iteration, and so on.

Now my questions are:

  1. How can I use a and b as global variables?
  2. I want to assign XX:XX:XX:XX:XX, YY:YY:YY:YY:YY so that I can use them in different functions.
1
  • 1
    What do you mean, exactly, by "global variables"? You could just assign $a to something else in the loop.
    – slhck
    Commented Jun 18, 2014 at 5:49

1 Answer 1

0

It seems you need bash arrays
For your purpose you can write a script like

#!/bin/bash
i=0
while read a[$i] b[$i]; do 
  echo ${a[$i]}                # Print the current one a
  echo ${b[$i]}                # Print the current one b 
  i=$[ i+1 ]                   # Increment i
done < filename.txt  
#  do other stuffs...          # if you want
echo "$[ $i -1 ] Items read "  # The number of lines read
echo The second a was ${a[1]}  # Array starts from 0
echo Those are all b  ${b[*]}  # You can print all together
  1. It depends from what you mean for global. Sadly you cannot simply export them outside of your script. From the man bash on bash 4.3.11(1)-release you can read.

    Array variables may not (yet) be exported.

  2. Inside your script you can use the array as normal variable. Instead of echo $a you have to refer to them with something like echo ${a[0]} or echo ${b[2]}...
    Note that you need to put {} to protect them.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .