0

I have following bash script:

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
echo ${nameserver}

Output shows dns1dns2dns2

How to echo array whit comma separated values? Example : dns1, dns2, dns3

Thanks.

dilbar
  • 5
  • 2
  • 2
    Notice that though you declare `nameserver` as an array, you're creating just a single string; you have to use `nameserver+=("$dns")` to append array elements. – Benjamin W. Sep 07 '22 at 11:12
  • The question has been closed while I've wrote my answer so I'll leave it here. You've created an array 'nameserver' with this `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+=$dns` append new value of `$dns` var into `$nameserver` var. That is why you've got 'dns1dns2dns2' in the end. – Ivan Sep 07 '22 at 11:23
  • 1
    To append an array(add new items) you have to use this code: `nameserver+=("$dns")` as Jetchisel suggested. Or use your counter($n) and fill your array like this: `nameserver[$n]="$dns"`. Then you can use `printf` for 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 ', '. – Ivan Sep 07 '22 at 11:23

1 Answers1

2

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 ( ).

Jetchisel
  • 7,493
  • 2
  • 19
  • 18