How Can I 'Echo' out Things Without a Newline?

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?

13

5 Answers

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"
7
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

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' ' '

You can also do it this way:

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

If, for whatever reason, -n doesn't fix this for you, you can also add \c to the end of the thing to be echo'd:

echo "$x\c"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest