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