24

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?

6 Answers 6

42

Simple way to print in one line

echo "${myArray[*]}"

Example:

myArray=(
one
two
three
four
[5]=five
)

echo "${myArray[*]}"

#Result
one two three four five
Sign up to request clarification or add additional context in comments.

2 Comments

What if I wanted formatted output (e.g. comma separated list of single quoted strings)
@Prachi Use this echo $(IFS=',';echo "${myArray[*]// /|}";IFS=$'') , link stackoverflow.com/a/13471141/5287072
8

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

readarray -t myArray < "$1"

Comments

7

One way :

printf '%s\n' "${myArray[@]}" | paste -sd ' ' -

The - is not mandatory on Linux, but could be necessary on some Unices*

or simply :

printf '%s ' "${myArray[@]}"

1 Comment

Using * is affected by the first character of "$IFS", which by default it happens to be an space. Using printf '%s ' "${myArray[@]}" is more robust.
3

My favourite trick is

echo $(echo "${myArray[@]}")

2 Comments

Invoking a subshell just for printing the array contents is unnecessarily expensive.
Without the subshell I was getting a newline inserted where there should have been a space.
2

@sorontar's solution posted in a comment was handy:

printf '%s ' "${myArray[@]}"

but in some places the leading space was unacceptable so I implemented this

local str
printf -v str ' %s' "${myArray[@]}"  # save to variable str without printing
printf '%s' "${str:1}"  # to remove the leading space 

Comments

1

In case you have the array elements coming from input, this is how you can

  • create an array
  • add elements to it
  • then print the array in a single line

The script:

#!/usr/bin/env bash

declare -a array
var=0
while read line
do
  array[var]=$line
  var=$((var+1))
done

# At this point, the user would enter text. EOF by itself ends entry.

echo ${array[@]}

1 Comment

I am not able to format the code part as a code. Someone help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.