store the names in an array as you read them, the iterate over the array adding whatever seperator is appropriate depending on the position. the complicated part is the random sorting of the array, but borrowing the shuffle function from http://mywiki.wooledge.org/BashFAQ/026
gives something like:
Code:
shuffle() {
local i tmp size max rand
# $RANDOM % (i+1) is biased because of the limited range of $RANDOM
# Compensate by using a range which is a multiple of the array size.
size=${#array[*]}
max=$(( 32768 / size * size ))
for ((i=size-1; i>0; i--)); do
while (( (rand=$RANDOM) >= max )); do :; done
rand=$(( rand % (i+1) ))
tmp=${array[i]} array[i]=${array[rand]} array[rand]=$tmp
done
}
while true
do
read -p "enter a name or quit to exit: " name
[[ $name == quit ]] && break
array=("${array[@]}" "$name")
done
shuffle
i=0
for name in "${array[@]}"
do
((i++))
(( i > 1 )) && sep=", " || sep=""
(( i == ${#array[@]} )) && sep=" and "
printf "${sep}${name}"
done
Code:
$ ./1
enter a name or quit to exit: Donald Duck
enter a name or quit to exit: Daisy Duck
enter a name or quit to exit: Magica De Spell
enter a name or quit to exit: etc
enter a name or quit to exit: quit
Donald Duck, Magica De Spell, Daisy Duck and etc
Bookmarks