How to populate a bash array with a file's lines -


populating array file should basic, can't work.

    #!/bin/bash     declare -a     i=0     cat "file.txt" | while read line;         a[$i]="$line"         i=$(($i + 1))     done     echo "${a[0]}" 

this prints empty line. file contains lines "foo" , "bar", here's output bash -x:

    + declare -a     + i=0     + cat file.txt     + read line     + a[$i]=foo     + i=1     + read line     + a[$i]=bar     + i=2     + read line     + echo '' 

i can't readarray builtin working:

    #!/bin/bash     declare -a b     cat "file.txt" | readarray b     echo "${b[0]}"      + declare -a b     + cat file.txt     + readarray b     + echo '' 

what doing wrong here?

this basic bash pitfall: segments of pipeline execute in subshells default, means whatever variables create go out of scope when these subshells terminate (the current shell won't see them).

depending on version of bash you're using, have 2 options:

  • [bash v4.2+] execute shopt -s lastpipe before use pipeline ensure last pipeline segment runs in current shell.

  • use input redirection (<) instead of pipeline (or, in more complex cases, process substitution (<(...)) ensure while loop doesn't run in subshell:

 a=()  while ifs= read -r line;    a+=( "$line" )    # ...   done < "file.txt"  

in simple case of reading lines file, can read directly array ("${a[@]}", in example):

  • bash 4.x:

    • readarray -t < "file.txt"
  • earlier versions:

    • ifs=$'\n' read -r -d '' -a < "file.txt"

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -