How can I read user input as an array in Bash?

Here's one way to do it:

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

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:

  • The Advanced Bash-Scripting Guide has a great chapter on arrays

  • The manpage of the read builtin

  • 15 array examples from thegeekstuff.com


Read it using this:

read -a arr

And for printing, use:

for elem in ${arr[@]}
do 
  echo $elem
done

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

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

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

See http://mywiki.wooledge.org/BashFAQ/001 for more.

And as always, to avoid writing bugs read http://mywiki.wooledge.org/BashGuide and avoid the tldp-guides like the Advanced bash scripting guide.