Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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],......}
like image 949
Rock26 Avatar asked Feb 06 '23 11:02

Rock26


1 Answers

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}
like image 52
John1024 Avatar answered Mar 02 '23 16:03

John1024