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.

  • 3
    mapfile -t array <file – Costas Oct 2 '15 at 17:44
  • @Costas i am getting mapfile command not found error – Mathew Oct 2 '15 at 17:48
  • 1
    @Mathew mapfile requires bash version 4.0 or better. What OS are you on? OSX? – John1024 Oct 2 '15 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 Oct 2 '15 at 17:54
  • Do you have readlines command? – Costas Oct 2 '15 at 17:55
1
while IFS= read -r line
do
    array[${#array[*]}]="$line"
done <file
  • can i loop through the elements by: for test in "${array[@]}" ? – Mathew Oct 2 '15 at 18:05
  • 1
    You are free to try. Why do you ask for permission? – Costas Oct 3 '15 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.