Rock26
Rock26

Reputation: 199

Store array output to comma separated list in bash scripting

I have taken input from user into array. But I need to use them as comma separated list. How can I do that? Input in my case is path like (/usr/tmp/). I appreciate your help and time. Thank you !

Example:

read "Number of subdirectories : " count
for i in $(seq 1 $count)
do
    read -e -p " Subdir : $i: " arr[$i]
done

Expected Result:

$var = {arr[1],arr[2],arr[3],......}

Upvotes: 5

Views: 8710

Answers (1)

John1024
John1024

Reputation: 113844

If you have an array like this:

$ declare -p arr
declare -a arr='([1]="abc" [2]="def")'

You can display it in comma-separated format:

$ (IFS=,; echo "{${arr[*]}}")
{abc,def}

That output can be saved in a shell variable using command substitution:

$ var=$(IFS=,; echo "{${arr[*]}}")
$ echo "$var"
{abc,def}

Upvotes: 9

Related Questions