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?
Solution 1:
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:
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:
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:
You can also do it this way:
array=(1 2 3 4 5)
echo "${array[@]}"