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.

1
  • Why have you not used a while read loop? Commented Jun 14, 2017 at 20:07

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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=($(<myfilename.txt))' That causes an error (weird?): syntax error near unexpected token `(' so I removed the outer parentheses, which put me on the wrong track. I just thought I would give you some feedback on your script. Thank you for solving my problem!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.