I have successfully made a join function, which joins an array to a string using the delimeter:
function join() # Usage: string=$(join "delimeter" "${array[@]}" )
{
local array=( "${@:2}" )
OLD_IFS="$IFS"
IFS="$1"
local string="${array[*]}"
IFS="$OLD_IFS"
echo "$string"
}
I have also tried to make a split function which should do the opposite:
function split() # Usage: array=( $(split "delimeter" "$string") )
{
OLD_IFS="$IFS"
IFS="$1"
local array=( $2 )
IFS="$OLD_IFS"
echo "${array[@]}"
}
But, when I use the split command and the result contains spaces, it will not work as expected. Example:
array=( "foo" "bar" "baz" "foo bar" )
string=$(join "|" "${array[@]}")
echo $string
array=( $(split "|" "$string") )
for i in ${array[@]}
do
echo $i
done
The last element "foo bar" has been split too.
I think the solution is that you have to do array=( "$(split '|' "$string")" )
, but I do not know how to nest the quotes probably.