read array with spaces

arrays, bash

Solution

Use `declare` instead of `eval`:

declare -a "bar=( $( < foo.txt ) )"

This forces everything in the file to be treated as the right-hand side of the assignment. Using `eval`, the contents of the file can be interpreted as code. For example, if the file contains

Some text ); echo "you just erased all your files"; ( true

then the following is executed by `eval`:

bar=( Some text ); echo "you just erased all your files"; ( true )

The parentheses in the file balance the parentheses used outside the command substitution, resulting in the text between them in the file being executed as code rather than being used to populate the array.

Problem

Say I have the file `foo.txt` ``` "The" "quick brown" "fox" "jumps over" "the" "lazy dog." ``` I would like to read these "fields" from the file into an array. However my attempt is failing if the field has a space ``` $ read -a bar < foo.txt $ echo ${bar[0]} "The" $ echo ${bar[1]} "quick ```

Original source