Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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 | ./array_test.sh. –  Stefano Palazzo Mar 6 '11 at 7:48
add comment

2 Answers

up vote 5 down vote accepted

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:

share|improve this answer
1  
Thanks lot that's was helpful :)))) –  moata_u Mar 6 '11 at 12:10
1  
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
add comment

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.

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
add comment

Your Answer

 
discard

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.