I am trying to read a file containing lines into a Bash array.
I have tried the following so far:
Attempt1
a=( $( cat /path/to/filename ) )
Attempt2
index=0
while read line ; do
MYARRAY[$index]="$line"
index=$(($index+1))
done < /path/to/filename
Both attempts only return a one element array containing the first line of the file. What am I doing wrong?
I am running bash 4.1.5
Latest revision based on comment from BinaryZebra’s comment
and tested here. The addition of
command evalallows for the expression to be kept in the present execution environment while the expressions before are only held for the duration of the eval.Use $IFS that has no spaces\tabs, just newlines/CR
Also note that you may be setting the array just fine but reading it wrong – be sure to use both double-quotes
""and braces{}as in the example aboveEdit:
Please note the many warnings about my answer in comments about possible glob expansion, specifically gniourf-gniourf’s comments about my prior attempts to work around
With all those warnings in mind I’m still leaving this answer here (yes, bash 4 has been out for many years but I recall that some macs only 2/3 years old have pre-4 as default shell)
Other notes:
Can also follow drizzt’s suggestion below and replace a forked subshell+cat with
The other option I sometimes use is just set IFS into XIFS, then restore after. See also Sorpigal’s answer which does not need to bother with this