0

How can I store contents of a file in array, for example:

my file has :

a /n
b /n
c /n
d /n

I want to store each line in array, how can I?

I'm using bash 3 on OSX.

7
  • 3
    mapfile -t array <file
    – Costas
    Commented Oct 2, 2015 at 17:44
  • @Costas i am getting mapfile command not found error
    – Mathew
    Commented Oct 2, 2015 at 17:48
  • 1
    @Mathew mapfile requires bash version 4.0 or better. What OS are you on? OSX?
    – John1024
    Commented Oct 2, 2015 at 17:52
  • yes i am on OSX, but can you tell me a less recent way to doing this array storage because, I will need to run this script is older versions as well
    – Mathew
    Commented Oct 2, 2015 at 17:54
  • Do you have readlines command?
    – Costas
    Commented Oct 2, 2015 at 17:55

1 Answer 1

1
while IFS= read -r line
do
    array[${#array[*]}]="$line"
done <file
2
  • can i loop through the elements by: for test in "${array[@]}" ?
    – Mathew
    Commented Oct 2, 2015 at 18:05
  • 1
    You are free to try. Why do you ask for permission?
    – Costas
    Commented Oct 3, 2015 at 9:06

You must log in to answer this question.

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