Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read array with spaces

Tags:

arrays

bash

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
like image 884
Zombo Avatar asked Oct 19 '25 20:10

Zombo


2 Answers

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.

like image 149
chepner Avatar answered Oct 22 '25 10:10

chepner


This works

$ read < foo.txt

$ eval bar=($REPLY)

$ echo ${bar[0]}
The

$ echo ${bar[1]}
quick brown
like image 34
Zombo Avatar answered Oct 22 '25 12:10

Zombo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!