Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat array elements with comma and single quote - Bash

Tags:

arrays

bash

ifs

How to convert array elements with single quotes and comma in Bash.

arr=("element1" "element2" "element3")
#element1 element2 element3

Desired result 'element1','element2','element3'

From Martin Clayton answer comma seprated values are achieved using IFS,

SAVE_IFS="$IFS"
IFS=","
ARRJOIN="${arr[*]}"
IFS="$SAVE_IFS"

echo "$ARRJOIN"
#element1,element2,element3

But how to add single quotes to each element.

like image 701
Ishpreet Avatar asked Aug 21 '17 12:08

Ishpreet


1 Answers

[akshay@localhost tmp]$ arr=("element1" "element2" "element3")
[akshay@localhost tmp]$ joined=$(printf ",'%s'" "${arr[@]}")
[akshay@localhost tmp]$ echo ${joined:1}
'element1','element2','element3'
like image 174
Akshay Hegde Avatar answered Sep 20 '22 00:09

Akshay Hegde