Try using an array, and the mapfile
AKA readarray
built-in. See help mapfile
for details. If you provide an empty string as the argument to mapfile
's -d
option, it will use a NUL as the delimiter.
First, create a function that can join an array into a single string with an arbitrary separator:
$ joinarray() { local IFS="$1"; shift; echo "$*"; }
This uses the first argument as the output separator, then uses echo to print the remaining arguments as a single string. This isn't limited to joining arrays, it works with any arguments (arrays, scalar variables, fixed strings), but it's particularly useful when used with arrays. It's called joinarray
so it doesn't conflict with the standard join
command.
Then, using an array called "$array":
$ mapfile -d '' array < <(printf "%s\0" "x" "y" ) # read the data into $array
$ declare -p array # show that the data was read correctly
declare -a array=([0]="x" [1]="y")
$ joinarray + "${array[@]}" # output the array joined by + characters
x+y
declare -p
statement is NOT declaring an array.declare -p
prints an existing variable - it's only there to demonstrate that the data was correctly read into the array, Seehelp declare
. The array was created by themapfile
command. – cas Mar 06 '22 at 04:10