Clear a terminal screen for real [closed]
Asked Answered
P

12

462

Using the clear command on the terminal only fools the user into thinking the screen has been cleared...you can still see output from the previous commands when you scroll using the mouse. This makes life difficult when you are drowning in a tsunami of text.

Various solutions (escape code etc.) which can be found on the Internet are only variations of what the clear command already does.

So how do you clear the contents of a terminal in Linux for real?

Philbo answered 20/3, 2011 at 6:10 Comment(10)
I'd categorize this as "software tools commonly used by programmers" (mentioned in the FAQ as valid).Philbo
What you're really asking is "How can I clear the terminal's scroll-back buffer?" which is independent of the shell (Bash) or Ubuntu.Burgher
@spiderplant0 probably because AskUbuntu is the right place for this -- at this time. Didn't exist when this was asked, so it got closed as off topic, even though that isn't the case.Mcclain
That's a more general question, affecting not only Ubuntu or bash, as @Dennis noted. I'd change the topic "Clear the Ubuntu bash screen for real" --> "Clear a terminal screen for real"Aran
There are many different terminal types with which you can run Bash (the term "bash terminal" is meaningless). "Clearing" isn't applicable to all of them - sometimes, the nearest approximation is to tear the paper and bin/shred/burn/destroy the bit you don't want.Libation
Good point, updated the question.Philbo
reset, tput reset, and printf "\033c" do not work for me media.giphy.com/media/EEyLnBuIzVc9c82xoV/giphy.gifDessiedessma
For mac, this works like a charm : https://mcmap.net/q/63538/-how-can-i-clear-previous-output-in-terminal-in-mac-os-xShaped
All those solutions will not work in vim :term.Montelongo
It's interesting how this question supposedly doesn't meet the guidelines, but 456 people have found it useful.Amathist
P
574

Use the following command to do a clear screen instead of merely adding new lines ...

printf "\033c"

yes that's a 'printf' on the bash prompt.

You will probably want to define an alias though...

alias cls='printf "\033c"'

Explanation

\033 == \x1B == 27 == ESC

So this becomes <ESC>c which is the VT100 escape code for resetting the terminal. Here is some more information on terminal escape codes.

Edit

Here are a few other ways of doing it...

printf "\ec" #\e is ESC in bash
echo -en "\ec" #thanks @Jonathon Reinhart.
# -e    Enable interpretation of of backslash escapes
# -n    Do not output a new line

KDE

The above does not work on the KDE console (called Konsole) but there is hope! Use the following sequence of commands to clear the screen and the scroll-back buffer...

clear && echo -en "\e[3J"

Or perhaps use the following alias on KDE...

alias cls='clear && echo -en "\e[3J"'

I got the scroll-back clearing command from here.

Philbo answered 20/3, 2011 at 6:14 Comment(17)
This is actually terminal specific. "\033c" is ESC c which is the VT-XXX escape sequence for "Full Reset (RIS)". Almost all terminals people actually use these days are VT compatible, but if you ever find yourself using a weird terminal, this might not work. @vpit3833's answer is more likely to work assuming TERM is set correctly.Isochronal
printf is a Bash builtin (it's true that it's also a separate binary, but builtins have precedence and most modern shells have printf).Burgher
@SDX2000 Does this clear your scroll buffer? Wasn't that a requirement?? BTW if this is to monitor a chatty program's output, my favorite way to do that is to run (or tail) in emacs, then I created a binding that marks and kills the whole buffer.Limpkin
@SDX2000 OK ... I know you specified Ubuntu, and I assumed that these would behave similar on all "modern" terminal emulators. I initially tested on my MAC's terminal and it did not reset there, but it did reset on my Centos Linux.Limpkin
Yeah, I wouldn't rely on this if security is at stake. It would be safer to close the terminal and open a new one.Burgher
@Dennis Williamson 1st comment: Ok I have edited my answer to remove the reference to the separate binary. 2nd comment: Yes agreed!Philbo
which cls || echo 'printf "\033c"' | sudo tee /usr/bin/cls && sudo chmod 755 /usr/bin/cls will make you a neat clear-screen script using the above answer.Myrt
which rept || printf '#!/bin/bash\nwhile true;do cls; $@; sleep 1; done\n' | sudo tee /usr/bin/rept && sudo chmod 755 /usr/bin/rept will create a script that keeps repeating your program with the specified parameters with one second delay and clears the screen each time. This can be used for looping some perl-experiments for instance.Myrt
$0.02 a few years later, but i'm a student at CU. Asked my operating systems professor and he said this was an example of ANSI escape sequence: en.wikipedia.org/wiki/ANSI_escape_code This is an example of in-band signalling.Thetic
Worked perfectly on Linux. Didn't clear the scrollback on macOS.Kalahari
The solution for KDE is a solution for xterm and terminals that support xterm's escape sequences. The official list of xterm escape sequences is at invisible-island.net/xterm/ctlseqs/ctlseqs.html. (If you want to learn more about terminal escape sequences, see ANSI escape sequence).Omophagia
For those who are using the version of Ubuntu that can be downloaded from the Microsoft Store on Windows 10, the command clear && echo -en "\e[3J" works there, unlike all the others.Korwun
So, usually with Linux you have to add lines like this to a script so the alias gets set up when you log in. Where would you put this one?Kinata
clear && echo -en "\e[3J" works well for macos 10.15.x.Nicolanicolai
Trying this in python 3.7.2 and it does clear the screen. However, when I have more than one page worth of content in the terminal, it only clears all the content available to the current screen. However if you scroll back up, the old content is still there from previous screens. Is there a way to fix thisEncourage
What operating system are you on? And what do you mean by trying this in python? Are you using IDLE or just running the python REPL in some shell? If it's the latter then which shell are you using?Philbo
None of the approaches mentioned here work on macOS terminal in Big Sur 11.6.2Guerrilla
T
241

Try reset. It clears up the terminal screen but the previous commands can be accessed through arrow or whichever key binding you have.

Tilda answered 20/3, 2011 at 6:13 Comment(10)
Thanks! But it clears every thing including the prompt. See my answer for a solution which doesn't do this.Philbo
@SDX2000 Both clear the prompt, and then the shell generates a new one. The one disadvantage to reset is that it seems to be a bit slower (probably because it does more than just emit ESC c) but it's more portable.Isochronal
@Laurence thanks for the clarification...I tried reset but it was so slow that I assumed the prompt was cleared along with everything else. I will still prefer to use ESC c since I will probably never use any terminal other than the one Ubuntu uses. Though reset may come in handy someday when I am debugging a remote machine through the serial port etc.Philbo
@SDX2000 reset is also handy for those cases where your terminal gets badly mangled because you killed something (or catted a binary file) and it left your term in a mangled state. Ever get into a state where your prompt shows up but not your typing, and when you hit enter the new prompt shows up next to the previous prompt rather than below it? reset fixes that. That's actually all I ever use it for... I've never had a need/desire to clear my scroll-back buffer.Isochronal
Awesome, cleaner than any bash script. Easier too with no need for an alias. Very fast on my system. Thank you.Brazee
The one-second delay associated with reset is unbearable for me.Sparker
@orbfish It didn't clear all of the screen contents. I'm on High Sierra too.Newsman
@DilipRajBaral wield. You're using the default Mac term program?Helladic
@Helladic Yeah. Default terminal.Newsman
This should be the default answer imho. Magic numbers printed are never an answerRetiary
K
82
tput reset

That will do the trick!

Kotick answered 20/7, 2014 at 11:19 Comment(3)
Executes much faster than plain reset, but still does the job!Womankind
Faster than just resetLowney
Explanation of why it is faster: Why does the reset command include a delay?Burdened
I
10

None of the answers I read worked in PuTTY, so I found a comment on this article:

In the settings for your connection, under "Window->Behavior" you'll find a setting "System Menu Appears on ALT alone". Then CTRL + L, ALT, l (that's a lower case L) will scroll the screen and then clear the scrollback buffer.

(relevant to the OP because I am connecting to an Ubuntu server, but also apparently relevant no matter what your server is running.)

Itol answered 16/4, 2014 at 14:8 Comment(2)
A 3 year old comment from @Dennis Williamson led me to this answer.Itol
Also, given that in the "Window" settings of PuTTY you activated the "System menu appears on ALT-Space" you can rapidly do CTRL+L then ALT+Space, U which first clears the terminal window then resets the scrollback for real.Josefjosefa
H
8
  1. Clean the visible screen

     clear 
    
  2. Clean screen and clear buffer

     clear && clear 
    
  3. Clean and 1-sec delay

     reset
    
  4. Clean without 1-sec delay

     tput reset
    
Hage answered 8/5, 2021 at 15:39 Comment(0)
L
7

The following link will explain how to make that alias permanent so you don't have to keep typing it in.

https://askubuntu.com/questions/17536/how-do-i-create-a-permanent-bash-alias

These are the steps detailed at that link.

  1. vim ~/.bashrc or gedit ~/.bashrc or what ever text editor you like
  2. put alias cls='printf "\033c"' at the bottom of the file
  3. save and exit
  4. . ~/.bashrc (and yes there should be a space between . and ~)
  5. now check to see if everything worked!

I take no credit for this information just passing it along.

Linalool answered 29/1, 2014 at 17:55 Comment(1)
\033c is same thing as \x1bc, and \x1bc is the same thing as \u001bc. All three of those work!Gilburt
M
7

My favorite human friendly command for this is:

reset

Tested on xterm and VT100. It also helps after an abnormal program termination. Keeps the command buffer, so up-arrow will cycle through previous commands.

Mockery answered 13/2, 2015 at 7:54 Comment(0)
A
6

I know the solution employing printing of new lines isn't much supported, but if all else fails, why not? Especially where one is operating in an environment where someone else is likely to be able to see the screen, yet not able to keylog. One potential solution then, is the following alias:

alias c="printf '\r\n%.0s' {1..50}"

Then, to "clear" away the current contents of the screen (or rather, hide them), just type c+Enter at the terminal.

Andi answered 31/8, 2018 at 17:11 Comment(3)
My terminal is for some reason unable to clear scrollback history, none of these solutions work except just printing a bunch of newlines, I would just suggest a clear at the end so to reset the cursor back at the top though.Spirituous
@MaximilianBallard which TTY is this?Andi
st terminal, but I don't know if its the specific terminal itself as it doesn't have this issue on my other computer and I use the same one.Spirituous
A
5

Just to add that tmux scroll buffer does not clear with clear, reset or printf. You need to :clear-history. See link.

Anchorite answered 13/5, 2019 at 2:16 Comment(0)
W
3

With KDE and Ubuntu 12.04 LTS and the "Konsole" terminal, none of the posted answers work. However, pressing default keyboard shortcut CTRL+Shift+X does work! Source:

https://bugs.kde.org/show_bug.cgi?id=288913

Wirth answered 12/12, 2013 at 20:47 Comment(1)
This has been changed to CTRL+Shift+K in later KDE versions: bugs.kde.org/show_bug.cgi?id=282593Auspex
L
-2
echo -e "\e[3J"

This works in Linux Machines

Lucknow answered 4/7, 2018 at 12:5 Comment(1)
Though we thank you for your answer, it would be better if it provided additional value on top of the other answers. In this case, your answer does not provide additional value, since another user already posted that solution. If a previous answer was helpful to you, you should vote it up instead of repeating the same information.Libation
M
-57

Compile this app.

#include <iostream>
#include <cstring>

int main()
{
  char str[1000];
  memset(str, '\n', 999);
  str[999] = 0;
  std::cout << str << std::endl;
  return 0;
}
Millham answered 9/12, 2011 at 6:10 Comment(5)
Sorry, but this isn't the best solution. There are better methods than spewing 999 newlinesEluviation
There actually is some value to this. In some terminals, clearing the screen with the other methods will kill the history and not allow you to scroll back... although with 999 lines my finger would get tired. Poor guy.Shift
@Shift The whole point of the question was that OP did not want to be able to scroll back after clearing.Indus
@Indus My comment was addressing this -50 poorly-rated answer, not the OP. But you're right!Shift
I daren't post this as an answer, but you could do something like this in bash with head -c999 /dev/zero | tr '\0' '\n', or yes '' | head -999Capuano

© 2022 - 2024 — McMap. All rights reserved.