Search code examples
arraysbashperformanceconcatenation

Bash concatenate array entries without spaces in between


Problem

I'm writing an bash script (version 4.3.48). There I have an array and want to concatenate all entries as a single string. The following code do such task (but lag in some case):

declare -a array=(one two three)
echo "${array[@]}"

Unfortunately I get this output, including spaces in between the array entries:

one two three

But what I actually need is this:

onetwothree


Background

I try to avoid using a for-loop and concatenate it on my own, cause I call this very often (more than each second) and I guess such a loop is much more expensive than use a build-in function.

So any suggestions how to obtain the required result?


Solution

  • printf gives you a lot more control over formatting, and it is also a bash builtin:

    printf %s "${array[@]}" $'\n'
    

    (That works because the shell's printf keeps on repeating the pattern until the arguments are all used up.)