Carriage return with echo command
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.
Related videos on Youtube
Dip
Updated on September 18, 2022Comments
-
Dip almost 2 years
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 belowecho -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?
-
Kusalananda almost 7 yearsThis is not reproducible. The second command results in the output
␣my college
, just like the first one. -
tripleee almost 7 years
echo -e
is notoriously unportable. You shoud probably useprintf
instead. -
George Vasiliou almost 7 years
-
-
Trevor Boyd Smith over 5 yearscarriage return is also used in the sysvinit provided functions. For example the function
echo_success
from/etc/init.d/functions
.