How can I 'echo' out things without a newline?

Bash

Bash Problem Overview


I have the following code:

for x in "${array[@]}"
do
  echo "$x"
done

The results are something like this (I sort these later in some cases):

1
2
3
4
5

Is there a way to print it as 1 2 3 4 5 instead? Without adding a newline every time?

Bash Solutions


Solution 1 - Bash

Yes. Use the -n option:

echo -n "$x"

From help echo: > -n do not append a newline

This would strips off the last newline too, so if you want you can add a final newline after the loop:

for ...; do ...; done; echo

Note:

This is not portable among various implementations of echo builtin/external executable. The portable way would be to use printf instead:

printf '%s' "$x"

Solution 2 - Bash

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

printf '%s\n' -- more robust than echo and you want the newlines here for sort's sake "${array[@]}" -- quotes unnecessary for your particular array, but good practice as you don't generally want word-spliting and glob expansions there

Solution 3 - Bash

You don't need a for loop to sort numbers from an array.

Use process substitution like this:

sort <(printf "%s\n" "${array[@]}")

To remove new lines, use:

sort <(printf "%s\n" "${array[@]}") | tr '\n' ' '

Solution 4 - Bash

You can also do it this way:

array=(1 2 3 4 5)
echo "${array[@]}"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionricky162View Question on Stackoverflow
Solution 1 - BashheemaylView Answer on Stackoverflow
Solution 2 - BashPSkocikView Answer on Stackoverflow
Solution 3 - BashanubhavaView Answer on Stackoverflow
Solution 4 - BashezzeddinView Answer on Stackoverflow