1

I have a two line prompt like below. Is there a command like clear that will clear the screen but keep both lines of the prompt visible?

~/current/directory git-branch*
$ echo 'hello...
Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Joe
  • 3,370
  • 4
  • 33
  • 56

1 Answers1

1

short: no, there's no such command.

long: you could write a script. Here's a brief introduction to the topic.

The clear program clears the whole screen. Your shell will draw a new prompt (at the top of the newly cleared screen). But suppose that you wanted to clear parts of the screen before your command completes, and returns to the shell.

Most terminals that you would use support the ANSI escape sequence which clears from the current cursor location to the end of the screen, which is the terminfo capability ed:

   clr_eos                   ed     cd   clear to end of
                                         screen (P*)

shown by infocmp as ed=\E[J.

You can use it in a script, e.g., using tput:

tput ed

This is one of the areas where "ansi.sys" differs from the ANSI standard (actually ECMA-48, see 8.3.29 ERASE IN PAGE). ansi.sys clears the entire screen when it receives

printf '\033]J'

Some people hard-code this into scripts, and assume that "ansi.sys" matches the standard. See for example How do I get color with VT100? in the ncurses FAQ.

Noting a comment about how to test this: likely there is nothing on your screen below the prompt. So typing tput ed may appear to do nothing. As noted above, it clears below the cursor. If you want to clear above the (2-line) prompt, that's a little more complicated:

  • save the cursor position
  • move the cursor up two lines
  • clear before the cursor
  • restore the cursor position.

If your prompt happens to be on the first line of the screen, this could be detected using the cursor position report. But that's more complicated to do than the question as phrased would anticipate. Assume that there's space above:

tput sc
tput cuu 2
tput cub 999
printf '\033[1J'
tput rc

A regular printf rather than tput is used here, because there's no predefined terminfo (or termcap) capability defined for that type of erase.

If you wanted to handle the case where the prompt starts in the top line of the terminal, you'd have to find the current line number and decide whether to do the clearing above (or not).

Further reading:

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
  • Nor `tput ed` or `printf '\033]J'` are working in `konsole`. –  Aug 04 '16 at 11:00
  • Neither `tput ed` nor `printf '\033]J'` worked in st (suckless terminal). Both commands simply return. In xterm, `printf '\033]J'` hangs. – Joe Aug 04 '16 at 17:46
  • I wouldn't expect it to work, since that's **`OSC J`** rather than **`CSI J`**. xterm handles it as expected. Starting from that point, the comment regarding konsole and tput needs some clarification (konsole works as expected also...). – Thomas Dickey Aug 04 '16 at 19:27