2

I am using bash on Mac OS X as well as Lubuntu. One of the annoying things about when I make console applications is that

clear

will add a whole (x-number) of lines to the console. And then I rewrite the screen, which is time consuming and inefficient.

Instead I am looking for a way to make my app not create extra lines and rewrite characters that are currently shown. (like the "top" command)

For example, my app needs to make a number in the upper left corner of the console go up as fast as possible.

Example #1: Using clear

#!/bin/bash
for i in `seq 1 1000000`
do
    echo $i
    clear
done

This would be great besides that it "flickers", hangs sometimes, wastes console space, and is generally ugly.

Example #2: Using backspace

#!/bin/bash
echo -e "\033[8;5;10;t"
clear
echo -e -n "0"

for i in `seq 1 1000000`
    do
    echo -e -n "\b\b\b\b\b\b\b$i"
done

This one runs like a charm, doesn't create extra lines, and is quick, but it can only be run in small windows.

Example #3: Using the sort of rewriting formula that "top" and "alsamixer" do.

How would I do this example?

2 Answers 2

6

Take a look at this; in particular I'd recommend the tput example, since that permits more or less exactly what you have in mind, and is fairly lightweight in a shell script -- which echoing escape sequences directly is not. tput also respects termcap/terminfo, which will help to make your scripts more portable.

4
  • I concur. tput is the way to go. You can check an example of tput usage here: wondershell.blogspot.de/2013/01/cpu-usage-graph-in-console.html
    – mnmnc
    Mar 29, 2013 at 14:40
  • @Aaron Miller Does tput work on all UNIX-like systems?
    – Blue Ice
    Mar 29, 2013 at 14:42
  • tput should work on anything that interprets ANSI escape sequences, which should cover just about all terminal emulators you'd find on a Unix/Linux/&c. system, and considerably more besides. Mar 29, 2013 at 15:10
  • tput forks a process and is far slower than echoing escape sequences directly (something like 150x slower on my computer!) Mar 15, 2021 at 19:57
2

You are looking for \r, the carriage return character. It causes new text to overwrite whatever is at the cursor's position:

#!/bin/bash
for i in `seq 1 1000000`
    do
    echo -e -n "$i\r"
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .