Carriage return for reprinting on the same line

while true; do echo -ne "$(date)\r"; sleep 1; done
The above code is just an example of printing on the same line, hit Ctrl + C to stop When using echo -ne "something\r", echo will: - print "something" - dont print a new line (-n) - interpret \r as carriage return, going back to the start of the line (-e) Remember to print some white spaces after the output if your command will print lines of different sizes, mainly if one line will be smaller than the previous Edit from reading comments: You can achieve the same effect using printf (more standardized than echo): while true; do printf "%-80s\r" "$(date)"; sleep 1; done

By: polaco
2009-11-17 22:45:37

What Others Think

Using terminfo here is better, IMO. Just using '\r' will not clear out junk characters on the end left by previous iterations of the loop. el1=$(tput el1); while true; do echo -ne "${el1}\r$(ps -eo %cpu,comm --sort %cpu|tail -1)"; sleep 1; done
arcege · 618 weeks and 2 days ago
Note that there are various implementations of the echo command, and not all of them support backslash codes. Also, many shells have a builtin echo command that behaves differently from /bin/echo. Therefore it is better to use printf which is standardized, so echo -ne $(date) becomes printf "%s\r" $(date) You can also easily get rid of the junk character problem that arcege mentioned: printf "%-79\r" $(date) Explanation: The "-" modifier will print the argument left-justified and overwrite the rest of the line with spaces. This assumes at least 80 characters per line, which should be more sufficient because the output from the date command is much shorter.
inof · 618 weeks and 1 day ago
That should be: printf "%s\r" "$(date)"
cfajohnson · 618 weeks ago
Thanks for the additions guys, i edited the command
polaco · 617 weeks and 4 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: