Tuesday, October 4, 2022

[SOLVED] Bash. Create array comma separated

Issue

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.


Solution

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



Answered By - Jetchisel
Answer Checked By - Timothy Miller (WPSolving Admin)