Untested but you can try an adjustment from your code.
declare -a nameserver=()
for ((n=1; n<=5; n++))
do
read -p 'Enter DNS'$n' ? : ' dns
if [ ! -z "$dns" ]
then
nameserver+=("$dns")
else
break
fi
done
(IFS=,;printf '%s' "${nameserver[*]}")
A space separated with a comma.
printf -v output '%s' "${nameserver[*]/%/,}"
Remove the trailing comma.
echo "${output%,*}"
Although technically the $* same with "${nameserver[*]}" is not an array anymore, it is just a single string. So what you're asking for is a bit weird, unless you're trying to create a csv format or a python array.
Instead of negating the -z, just use -n without the bang ! e.g.
[ -n "$dns" ]
nameserver is declared as and array but you're assigning a variable nameserver+= an array needs a ( ).
nameserveras an array, you're creating just a single string; you have to usenameserver+=("$dns")to append array elements.declare -a nameserver=()but in the loop you are appending not the array(not adding new items to an array) but appending just the first item of it(${nameserver[0]}) which is correspond with the variable$nameserver. This code:nameserver+=$dnsappend new value of$dnsvar into$nameservervar. That is why you've got 'dns1dns2dns2' in the end.nameserver+=("$dns")as Jetchisel suggested. Or use your counter($n) and fill your array like this:nameserver[$n]="$dns". Then you can useprintffor pretty print the desired output, like so:printf '%s, ' "${nameserver[@]}"But if you need only the CSV, then a var is enough, append it like so:nameserver+="$dns, ", then echo like this:echo ${nameserver%, }to drop the last ', '.