1

I have read input from file using:

declare -a ARR      
    readarray -t ARR < <(cat /etc/passwd | tr "\n" "\n" )

This prints it fine, but I want to access each line:

 printf '%s\n' "${ARR[@]}

This is splitting the input on spaces:

for i in ${ARR[@]}; do
        echo ${i}
    done

Does echo requires a particular option to print it correctly? Based on this answer, changing it to echo "${i}" should fix it, but it doesn't. This has the same problem:

printf "${i} \n"
Burrough Clarke
  • 522
  • 4
  • 19

1 Answers1

2

To avoid splitting on spaces, replace:

for i in ${ARR[@]}; do

With:

for i in "${ARR[@]}"; do

Without the double-quotes, the shell does word-splitting.

It would also be best to replace echo ${i} with echo "${i}". Without the double-quotes the ${i} will be subject to word-splitting (which will cause multiple spaces to be collapsed to one blank) and pathname expansion (which may cause words with shell-active characters to be replaced with filenames from the current directory).

John1024
  • 109,961
  • 14
  • 137
  • 171
  • 1
    Most variable/array/command expansions should be in double-quotes. There are some situations where it's safe to leave the double-quotes off, but IMO it's more bother to keep track of where it's safe, than it is to just always use double-quotes. – Gordon Davisson Dec 31 '17 at 08:20
  • Note that, inside double quotes, `"${ARR[*]}"` uses the first character of `$IFS` for its separator. – cdarke Dec 31 '17 at 09:11