0

This is probably going to be marked as duplicate, but after reading several posts, I still can't make my bash script work. I have a text file with multiple lines; each line has 1 string only. I want to import the content to a bash variable, such as each line is a separate element. So, as an example, if MYVAR is the mentioned variable, I want to be able to access any element by its position, e.g.:

for i in $(seq 0 2)
do
        echo ${MYVAR[$i]}
done

The above is just an example; I do not need a for loop, that is why i have not used while read LINE strategy. I have tried several ways, but the file keeps being imported as 1 long string which includes the whole content. Hope my purpose is clear, I appreciate any help.

Max_IT
  • 602
  • 5
  • 15

1 Answers1

1

change the IFS to newline only, and read the file into array with ():

OFS=$IFS
IFS=$'\n'
MYVAR=($(<myfilename.txt))
for i in $(seq 0 2)
do
        echo ${MYVAR[$i]}
done
# setup the IFS to its original value
IFS=$OFS
Tamar
  • 669
  • 3
  • 9
  • 1
    Thank you, it worked! This morning, with a fresher mind, I reviewed my script. What puzzled me is that IFS by default should be space, newline and tab. Thus, the script above should work (and it does) even without changing IFS. I realized that one of my initial mistakes was to put a space after the '=' in 'MYVAR=($( – Max_IT Jun 15 '17 at 13:14