arraysbashprintfecho

How to print a bash array on the same line


I am reading in filetype data into a bash array and need to print its contents out on the same line with spaces.

#!/bin/bash

filename=$1
declare -a myArray

readarray myArray < $1

echo "${myArray[@]}" 

I try this and even with the echo -n flag it still prints on newlines, what am I missing, would printf work better?


Solution

  • readarray retains the trailing newline in each array element. To strip them, use the -t option.

    readarray -t myArray < "$1"