I answered this on StackOverflow a few months ago, see Overwriting last terminal output(multiple lines). While I suppose it is possible that OP meant to print literally "line1", "line2", etc., that would only be of interest in a classroom exercise. Real programs print more interesting things, so I am answering that question. As before, the current q/a overlooks the problem when updated lines are shorter than the existing line. Addressing that
echo "line1"; tput el
echo "line2"; tput el
echo "line3"; tput el
echo "line4"; tput el
# without using clear cmd, next cycle line1 should be printed
# in line1 place not in a new line , and same for other lines
cuu is a good alternative, using
grep to check the availability of a capability seems less effective than using
tput itself, e.g.,
[[ -z "$restore" ]] && restore=$(tput cuu 4)
[[ -z "$restore" ]] && restore=$(tput cuu1; tput cuu1; tput cuu1; tput cuu1)
which is still a little crude in the way the number of lines is embedded in the expressions. But then you could just execute
$restore at the end of the loop.
Something similar could be done with the check for
el in the terminal.
Given that this is bash, the
echo "line1", etc., should really be a function (which would eliminate the redundant
tput el calls).
All of these capabilities are likely to be supported with terminals that OP is likely to encounter. The save/restore cursor controls are a weak point, since there are two main variants:
DECRC (supported by xterm - see XTerm Control Sequences):
ESC 7 Save Cursor (DECSC).
ESC 8 Restore Cursor (DECRC).
ANSI.SYS (also supported by xterm, but not by all "xterm emulators"):
CSI s Save cursor (ANSI.SYS), available only when DECLRMM is disabled.
CSI u Restore cursor (ANSI.SYS).
Other useful sources of information:
The question, by the way, is mis-titled, since the example given (and so far none of the answers) uses scrolling. One could (again referring to terminfo, and limiting oneself to VT100-like terminals such as xterm) use scrolling regions. The place to start would be here (from the terminfo manual page):
change_scroll_region csr cs change region to
line #1 to line #2