Clear a terminal screen for real
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.
Clearing the screen by printing a character?
If you want to clear the screen, the "ANSI" sequence in a printf
\033[2J
clears the entire screen, e.g.,
printf '\033[2J'
The command-line clear
program uses this, along with moving the cursor to the "home" position, again an "ANSI" sequence:
\033[H
The program gets the information from the terminal database. For example, for TERM=vt100
, it might see this (using \E
as \033
):
clear=\E[H\E[J$<50>
(the $<50>
indicates padding needed for real VT100s). You might notice that the 2
is absent from this string. That is because the cursor is first moved to the home (upper left) position, and the 2
(entire screen) is not necessary. Eliminating that from the string made VT100s a little faster.
On the other hand, if you just want to reset the terminal, you can use the VT100-style RIS
:
\033c
but that has side-effects, besides not being in ECMA-48. These bug reports were for side-effects of \033c
:
- Debian Bug report logs - #60377
"reset" broken for dumb terminals - Debian Bug report logs - #239205
"reset changes a unicode console to non-unicode"
Further reading:
- Why doesn't the screen clear when I type control/L?
- XTerm Control Sequences
CSI Ps J Erase in Display (ED).
Ps = 0 -> Erase Below (default).
Ps = 1 -> Erase Above.
Ps = 2 -> Erase All.
Ps = 3 -> Erase Saved Lines (xterm).
- ECMA-48: Control Functions for Coded Character Sets
Clear terminal in Python
What about escape sequences?
print(chr(27) + "[2J")
How to clear the entire terminal (PowerShell)
To also clear the scrollback buffer, not just the visible portion of the terminal in Visual Studio Code's integrated terminal, use one of the following methods:
Use the command palette:
- Press Ctrl+Shift+P and type
tclear
to match theTerminal: Clear
command and press Enter
- Press Ctrl+Shift+P and type
Use the integrated terminal's context menu:
- Right-click in the terminal and select
Clear
from the context menu. - On Windows, you may have to enable the integrated terminal's context menu first, given that by default right-clicking pastes text from the clipboard:
Open the settings (Ctrl+,) and change settingterminal.integrated.rightClickBehavior
to eitherdefault
orselectWord
(the latter selects the word under the cursor before showing the context menu).
- Right-click in the terminal and select
Use a keybord shortcut from inside the integrated terminal:
- On Windows, use Ctrl+K, the default.
- As of VSCode 1.30.1, on macOS, a default exists, Cmd+K, but doesn't work, whereas on Linux there is no default at all.
The solution in both cases is to define a custom key binding as follows, by directly editing filekeybindings.json
(commandPreferences: Open Keyboard Shortcuts File
from the command palette):
{
"key": "ctrl+k", // on macOS, alternatively use "cmd+k"
"command": "workbench.action.terminal.clear",
"when": "terminalFocus" // To avoid conflicts with Ctrl+K *chords* elsewhere
}
Using a command you can invoke from a shell in the integrated terminal:
Note: A truly cross-platform solution would require executing the VSCode-internal workbench.action.terminal.clear
command from a shell, but I don't know how to do that / if it is possible at all - do tell us if you know.
Linux (at least as observed on Ubuntu):
- Use the standard
clear
utility (/usr/bin/clear
), which also clears the scrollback buffer.
- Use the standard
macOS:
Print the following ANSI control sequence (unfortunately, the standard
/usr/bin/clear
utility clears only one screenful, not also the scrollback buffer):'\e[2J\e[3J\e[H'
(\e
represents the ESC char. (0x1b
,27
); e.g., frombash
:printf '\e[2J\e[3J\e[H'
You can easily wrap this call in a shell script for use from any shell: create a file named, say,
cclear
, in a directory listed in your system'sPATH
variable, then make it executable withchmod a+x
; then save the following content to it:#!/bin/bash
# Clears the terminal screen *and the scrollback buffer*.
# (Needed only on macOS, where /usr/bin/clear doesn't do the latter.)
printf '\e[2J\e[3J\e[H'
Windows:
- NO solution that I'm aware of:
cmd.exe
's internalcls
command and PowerShell's internalClear-Host
command clear only one screenful in the integrated terminal (not also the scrollback buffer - even though they also do the latter in a regular console window and in Windows Terminal).
- NO solution that I'm aware of:
How can I clear the terminal in Visual Studio Code?
Use Ctrl+K. This goes clean your console in Visual Studio Code.
Per comments, in later versions of VSCode (1.29 and above) this shortcut is missing / needs to be created manually.
- Navigate:
File
>Preferences
>Keyboard Shortcuts
- search for
workbench.action.terminal.clear
- If it has no mapping or you wish to change the mapping, continue; otherwise note & use the existing mapping
- Double click on this entry & you'll be prompted for a key binding. Hold
CTRL
and tapK
.Ctrl + K
should now be listed. Press enter to save this mapping - Right click the entry and select
Change when expression
. TypeterminalFocus
then press enter. - That's it. Now, when the terminal is in focus and you press Ctrl+K you'll get the behaviour you'd have expected to get from running
clear
/cls
.
How can I clear previous output in Terminal in Mac OS X?
To clear the terminal manually:
⌘+K
Command+K for newer keyboards
To clear the terminal from within a shell script;
/usr/bin/osascript -e 'tell application "System Events" to tell process "Terminal" to keystroke "k" using command down'
clear the screen in C without printing control characters
The actual sequence is "\033[3J\033[H\033[2J"
, and contains three ANSI escape codes:
"\033[3J"
= CSI 3 J: Clear terminal screen and delete everything in the scrollback buffer. Specific to xterm-like terminals."\033[H"
= CSI H: Move cursor to top left corner."\033[2J"
= CSI 2 J: Clear terminal screen.
While these sequences work for most (if not all) current terminal emulators, the actual codes generated are from the POSIX terminal interface database for the current terminal. So, it is not a good idea to hard-code the sequence, but use the terminal interface.
To use the terminal interface, you use ncurses. You can use either the C library interface, or the command-line utilities (clear
or reset
, the latter resetting the terminal properties back to normal/defaults, in case a previous program left them in an odd or unusable state).
Not wanting to use the terminal interface but wanting to clear the terminal is an odd combination; atypical in the Unix or POSIX environments. You should reconsider why you want this. For example, if it is just because you find it easier to read the output, just pipe the output through less
, or run clear ; ./yourprog
instead.
In the MS-DOS era, over two decades ago, the idiom system("cls");
was common. This executed an MS-DOS command, cls
, that cleared the screen. (If ANSI.SYS was loaded, then the ANSI escape sequence mentioned above would have worked just fine too.)
In Unix and POSIXy systems, you can use the isatty()
function to test if a file descriptor refers to a terminal. For maximum compatibility, you can use the macros STDIN_FILENO
, STDOUT_FILENO
, and STDERR_FILENO
for the three standard file descriptors, although in Linux, they are always 0, 1, and 2, respectively.
So, technically, you could use for example
if (isatty(1))
system("clear 2>/dev/null");
else
if (isatty(2))
system("clear >&2 2>/dev/null");
to check if standard output or standard error is a terminal, and if one is, use the ncurses clear
command-line command to clear it. Per POSIX.1, system()
uses a POSIX shell. The above commands use POSIX shell redirection to ensure the output of the command goes to the desired descriptor, and that any error messages from the shell or the command (say, if it does not exist) is redirected to the null device, i.e. discarded. This will therefore not output anything if both standard output and standard error are redirected to files or devices or anything not a terminal; it does not emit ANSI escape codes to redirected output.
Still, you should reconsider. It is atypical to bake in such features to simple command-line commands; and it is trivial to make shell aliases or wrapper scripts that do the clearing before executing your actual command, so there is no need for baking it in.
How can I clear the terminal screen in Go?
Note: Running a command to clear the screen is not a secure way. Check the other answers here as well.
You have to define a clear method for every different OS, like this. When the user's os is unsupported it panics
package main
import (
"fmt"
"os"
"os/exec"
"runtime"
"time"
)
var clear map[string]func() //create a map for storing clear funcs
func init() {
clear = make(map[string]func()) //Initialize it
clear["linux"] = func() {
cmd := exec.Command("clear") //Linux example, its tested
cmd.Stdout = os.Stdout
cmd.Run()
}
clear["windows"] = func() {
cmd := exec.Command("cmd", "/c", "cls") //Windows example, its tested
cmd.Stdout = os.Stdout
cmd.Run()
}
}
func CallClear() {
value, ok := clear[runtime.GOOS] //runtime.GOOS -> linux, windows, darwin etc.
if ok { //if we defined a clear func for that platform:
value() //we execute it
} else { //unsupported platform
panic("Your platform is unsupported! I can't clear terminal screen :(")
}
}
func main() {
fmt.Println("I will clean the screen in 2 seconds!")
time.Sleep(2 * time.Second)
CallClear()
fmt.Println("I'm alone...")
}
(the command execution is from @merosss' answer)
Related Topics
Rename File Command in Unix with Timestamp
Extract Average Time from Ping -C
Decrypt Obfuscated Perl Script
Automated Test Tools for Linux/Ncurses
Linux - Without Hardware Soundcard, Capture Audio Playback, and Record It to File
How to Set Cronjob with Non-Root User
Linux Raw Ethernet Socket Bind to Specific Protocol
How to Reset Emacs to Save Files in Utf-8-Unix Character Encoding
How to Print a String to the Terminal in X86-64 Assembly (Nasm) Without Syscall
Does Linux Time Division Processes or Threads
How to Strip Path While Archiving with Tar
Where to Get Msbuild for Linux
What Character Sequence Should I Not Allow in a Filename
How to Point a Docker Image to My .M2 Directory for Running Maven in Docker on a MAC
How to Create Virtual Environment for Python 3.7.0
Is It Necessary to Deregister a Socket from Epoll Before Closing It