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

Solution 1:

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

Solution 2:

Read it using this:

read -a arr

And for printing, use:

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