Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How could I read user input as an array? :)

share|improve this question
I'm presuming you want to read from stdin? My answer will also work with execution like cat war_and_peace.txt | ./ – Stefano Palazzo Mar 6 '11 at 7:48
Or simply ./ < war_and_peace.txt. – Eliah Kagan May 11 '15 at 18:13
up vote 8 down vote accepted

Here's one way to do it:

while read line
    my_array=("${my_array[@]}" $line)

echo ${my_array[@]}

If you just run it, it will keep reading from standard-input until you hit Ctrl+D (EOF). Afterwards, the lines you entered will be in my_array. Some may find this code confusing. The body of the loop basically says my_array = my_array + element.

Some interesting pieces of documentation:

share|improve this answer
Thanks lot that's was helpful :)))) – moata_u Mar 6 '11 at 12:10
read -r is quite useful/important sometimes... Stefano's link to the "read builtin manpage" explains its purpose...(to prevent backslash interpretation). – Peter.O Mar 9 '11 at 5:04

And one that doesn't recreate the array each time (though requires bash 3.1 or newer):

while IFS= read -r -p "Next item (end with an empty line): " line; do
    [[ $line ]] || break  # break if line is empty

printf '%s\n' "Items read:"
printf '  «%s»\n' "${array[@]}"

See for more.

And as always, to avoid writing bugs read and avoid the tldp-guides like the Advanced bash scripting guide.

share|improve this answer
Nice links... Thanks for pointing out the IFS issue. Without nulling it, 'read' sripts all leading and trailing whitespace... and of course the -r too... – Peter.O Mar 9 '11 at 5:20

Read it using this:

read -a arr

And for printing, use:

for a in ${arr[@]}
  echo $a
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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