Echo outputting results in erratic order in BASH Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Echo outputting results in erratic order in BASH without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Word of warning: I’m relatively new to BASH scripting, so any advice on my hacky scripting is appreciated.

I have a strange issue, in my code I’ve collected a bunch of error strings from a file in one array, and a second array stores the count of the errors in the same index (I did this given the lack of 2D arrays, and didn’t really want to approach building a matrix).

When outputting the code I use this line:

for ((i=0; i<${#NAME_ARRAY[@]}; i++)); do
   echo "Error: ${NAME_ARRAY[$i]} x ${COUNT_ARRAY[$i]}"

In this case I’m testing with two separate files, if I run it on file one I get this output:

Error: Exception: unknown/unregistered file format : x 72982

That’s cool, works fine and exactly as expected. I know there is only one error (“Exception: unknown/unregistered file format : “) in the huge log file, and that it appears 72982 times.

But in my other case I get this result:

x 66964xception: Some kind of disk I/O error occurred

Here’s where I’m utterly lost. If I print out ${NAME_ARRAY[$i]} individually, I get “Some kind of disk I/O error occurred” perfectly fine. Similarly if I print out ${COUNT_ARRAY[$i]} by itself I get “66964”…but when I put them both in a string, the COUNT_ARRAY number gets thrown into the start of my string and overrides the “Error: ” part.

Figuring I could be a little smart and a lot hacky, I decided to do this:

echo -n "Error: ${NAME_ARRAY[$i]}"
echo " x ${COUNT_ARRAY[$i]}"

My amateur mind thought this would separate the two outputs (in case of any sort of threading/priority issues) but alas, I still get the exact same result.

Am I missing something extraordinarily obvious? Or are my echos doing something weird.

I also just tested using printf instead of echo and the same thing happens. Could there be some sort of character encoding issue that’s stuffing up when printing to console?


The “Some kind of disk I/O error occurred” message is very likely to contain a r character at the end. This resets the cursor to the beginning of the current line, causing the ” x 66964″ which is output next to overwrite the beginning of the line. To fix it, you need to strip out the carriage return when you read it into $NAME_ARRAY, e.g. by piping through tr -d 'r'.

We are here to answer your question about Echo outputting results in erratic order in BASH - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji