23

I was practicing echo command with option \r (carriage return) as below.

echo -e "This is \r my college"

output:

 my college

but when I add one more word before \r as below

echo -e "This is the \r my college"

Then it gives me output like:

 my college the

Another example

echo -e "This is \r valid data"
 valid data

echo -e "This is not a \r valid data"
 valid data a

So, I wanted to know that what is the actual purpose of carriage return here?

ilkkachu
  • 138,973
Dip
  • 680

2 Answers2

39

The \r is just that, a "carriage return" - nothing else. This means what is after the \r will overwrite the beginning of what has already been printed.

For example:

echo -e "1234\r56"

Will display:

5634

echo has printed 1234 then gone back to the begining of the line and printed 56 over the top of 12.

For a new line, try \n instead. No need for spaces too. For example:

echo -e "This is\nmy college"

Which will output:

This is
my college

The carriage return is useful for things like this:

#!/bin/sh
i=0
while [ $i -lt 3 ]
do
    echo -ne "\r"`date` #you should remove new line too
    sleep 1
    i=$(($i + 1))
done
exit

Which will display date over the top of itself instead of creating a new line after each loop.

Tigger
  • 3,647
2

Tigger has a good answer about what the \r does. One other trick for the Bourne shell (which works in different ways in other shells) is to clear the end of the line like so:

#/bin/sh -e
echo "this is a first line...\r\c"
...other code...
echo "another line\033[K\r\c"

Without the \033[K (kill the end of the line), you would get:

another lineirst line...

With the \033[K the output from the cursor position to the end of the line is cleared so the result of the above is:

another line

This is practical for scripts that take a long time and you want to let the user know where you're at (i.e. maybe a path your script is working on and the next path is shorter).

Note: As a side note, I'd like to specify that the \n is what sends your cursor to the next line. In the old MS-DOS console, it just goes one line down, same column. This is why under MS-Windows you are still expected to write both characters (\r\n). Although in most cases people just write \n and things work as expected because the FILE has a "text mode" which inserts a \r before each \n (and also mangles binary files every so often...).

Alexis Wilke
  • 2,857