Как очистить терминал в linux
Перейти к содержимому

Как очистить терминал в linux

  • автор:

6 способов очистки терминала в Linux

Sep 27, 2018 07:01 · 191 words · 1 minute read tips ubuntu debian centos

Иногда при работе в терминале вызываемые команды и результаты их выполнения полностью “засоряют” экран и делают работу в консоли некомфортной. Давайте разберемся с несколькими способами быстрой очистки терминала в Linux!

На мой взгляд, самый простой и самый быстрый способ очистки терминала — использование комбинации клавиш ctrl+L ( control+L для MacOS).

Вторым широко известным способом очистки консоли является команда clear .

На третьем месте по частоте использования в целях очистки терминала находится команда reset .

Далее следуют несколько экзотические способы. Например, для очистки терминала можно ввести такую команду:

Естественно, это не так удобно в использовании, как первые три варианта, но мы можем сделать алиас:

И это уже не выглядит странно.

  1. Данный вариант можно использовать для очистки терминала в дистрибутивах с графической оболочкой KDE (там терминал по умолчанию называется Konsole):

Ну или сразу создаем алиас:

  1. В дистрибутивах с оболочкой GNOME (например, Ubuntu 18.04) можно самостоятельно назначить комбинацию клавиш, которая будет отвечать за очистку терминала, например:

Но, признаться, в повседневной работе мне вполне достаточно и самого первого способа очистки консоли, приведенного в этой статье.

Как очистить терминал Linux

Если вы хотите делать снимки экрана терминала Linux или вам хочется чтобы окно терминала перед выполнением команды с очень длинным выводом было пустым, вам понадобиться возможность очистки терминала.

Существует несколько способов это сделать. Можно воспользоваться горячей клавишей, или выполнить несколько команд. Можно очистить только текущий экран или полностью весь вывод. В сегодняшней статье мы расскажем как выполняется очистка терминала в Linux.

Как очистить терминал в Linux

Самый простой способ очистить терминал — воспользоваться сочетанием клавиш Ctrl + L. После нажатия этих клавиш весь уже существующий вывод переместиться вверх, так, что текущее окно терминала будет пустым:

Тем не менее вся история вывода не будет удалена, вы сможете легко получить к ней доступ просто пролистав немного вверх:

Но если вы не будете пытаться листать историю, окно будет чистым. Если этого вам мало, вы можете воспользоваться командой clear. Она полностью очищает вывод и к предыдущему выводу вы уже вернуться не сможете:

Для того чтобы утилита clear не очищала полностью историю вывода, доступную при прокрутке, а работала аналогично сочетанию клавиш Ctrl+L используйте опцию -x:

Но и у этой команды есть одна проблема. Если вы по ошибке вывели содержимое двоичного файла, ваш эмулятор может быть сломан. Все вводимые вами символы могут превратиться в кракозябры, а приглашение ввода вовсе перестанет работать. Такое происходит потому что в двоичных файлах могут случайно встретиться какие-нибудь управляющие последовательности, ломающие работу терминала.

В такой ситуации команда clear не поможет, здесь нужна команда reset:

Она сбрасывает терминал полностью, не только предыдущий вывод, но и любые настройки, заданные с помощью управляющих последовательностей. После её выполнения вы получите чистый терминал.

Как видите, очистить терминал Linux очень просто. А какие способы знаете вы? Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

4 Useful Commands to Clear Linux Terminal Screen

Just like any other operating system, Linux also supports a rich Graphical User interface (GUI). In fact, it supports multiple graphical desktop environments such as – GNOME, KDE, Cinnamon, and the list goes on.

However, most Linux administrators and power users prefer to use the command line interface, because it allows us to automate repetitive tasks using the scripts.

One of the trivial downsides of this approach is that often times the terminal gets filled up with the command’s or script’s output. So, in some cases, cleaning up the terminal becomes necessary.

In this guide, we will discuss various methods that allow us to clean up the Linux terminal. After following this guide, Linux users can use one of the methods while working with Linux’s command line interface.

Table of Contents

1. Clear Linux Terminal Using clear Command

The clear command is one of the most commonly used commands for clearing the Linux terminal. This command simply clears the terminal screen including its scroll-back buffers.

To understand the usage of the command, let’s execute a few commands in the terminal:

Now, to clean up the screen, just execute the clear command without any argument:

2. Clear Linux Terminal Screen Using CTRL+L Shortcut

In a similar way, we can use the ctrl+L shortcut to clear the terminal screen. However, this method doesn’t clean up the scroll-back buffers.

To illustrate this, first clear the terminal screen using the ctrl+L shortcut and then scroll up the screen using the mouse:

Clear Terminal Using CTRL+L Shortcut

In this example, we can see the previous output by scrolling up the terminal.

3. Reset (Clear) Linux Terminal Using reset Command

Additionally, we can also use the reset command to clear the terminal screen. Just like the clear command the reset command also clears the scroll-back buffers.

The reset command reinitializes the terminal hence it takes more time compared to the clear command.

4. Clear the Terminal Using the Escape Code

We can use the <ESC>c escape code to clear the terminal. Let’s understand with a simple example.

In bash, we can use the \e escape sequence to represent the ESC character. So, to clear the terminal screen we can use the \ec string with the printf command as shown below:

In a similar way, we can use the \033 octal number to represent the ESC character. So to clear the terminal, we can use the \033c string with the printf command:

In addition to this, the hexadecimal number \x1B represents the ESC character. Hence we can use it to clear the screen:

In this guide, we discussed various methods for clearing the Linux terminal screen. Linux users can use one of the methods as per their choice.

Do you know of any other method for clearing the terminal in Linux? Let us know your views in the comments below.

How to really clear the terminal?

I can issue the clear command or press Ctrl + L to clear the current Ubuntu terminal, but this just shifts previous output upwards and if you use mouse scroll or PgUP and PgDown keys it’s hard to distinguish where the output of previous command ends and output of current command begins.

Is there a way to really clear the terminal so I won’t see previous command results?

12 Answers 12

Yes, the command you’re looking for is

In contrast to clear , or Ctrl + L , reset will actually completely re-initialise the terminal, instead of just clearing the screen. However, it won’t re-instantiate the shell (bash). That means that bash’s state is the same as before, just as if you were merely clearing the screen.

As @Ponkadoodle mentions in the comments, this command should do the same thing more quickly:

From the other answers:

You can set a Keyboard Shortcut to reset the terminal, as explained by towolf.

If you’re running Kubuntu, and your terminal is Konsole, you need to go to Edit → Clear history, since reset doesn’t work the same way there, as UncleZeiv notes.

BeastOfCaerbannog - On strike's user avatar

I was looking for this for a while and I found some genius that posted this:

Clears the whole screen buffer, very clean. Works on OS X and believe it works fine on most *nix terminals.

For curious, this part ‘\e[3J’ is a terminal escape command.

Goran's user avatar

/.bashrc and add alias reset="clear && printf '\e[3J'"

You can also assign a shortcut in gnome-terminal by going to Edit → Keyboard Shortcuts. I use Shift + Ctrl + Alt + C .

reset and clear shortcut

WinEunuuchs2Unix's user avatar

Cross posting my answer from stackoverflow.

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

yes that’s a ‘printf’ on the bash prompt.

You will probably want to define an alias though.

Explanation

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

Here are a few other ways of doing it.

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.

Or perhaps use the following alias on KDE.

I got the scroll-back clearing command from here.

run this command:

This has the same effect as launching a new terminal.

My favorite is printf «\ec» . This can also be printf «\033c» or printf «\x1bc» . That is an ansi escape sequence that miraculously clears the screen and buffer for the terminal output (for most standard terminals I have worked in it seems — I know it works in such as gnome-terminal, terminator, xterm, etc. on Ubuntu-like Linuxes)

I know this works in Linux Mint and Ubuntu 14.04, so I don’t know why people are appending and prepedning things like clear && echo -ne «\033c . printf «\ec» has always worked for me.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *