Очистить консоль в линукс

How to Clear Terminal Screen in Ubuntu and Other Linux Distributions [Beginner’s Tip]

When you are working in the terminal, often you’ll find that your terminal screen is filled up with too many commands and their outputs.

You may want to clear the terminal to declutter the screen and focus on the next task you are going to perform. Clearing the Linux terminal screen helps a lot, trust me.

Clear Linux terminal with clear command

So, how do you clear terminal in Linux? The simplest and the most common way is to use the clear command:

You need no option with the clear command. It’s that simple but there are some additional things you need to know about it.

The clear command and other methods of clearing screen may depend on the terminal emulator you are using. Terminal emulator is the terminal application that you use for accessing the Linux shell (command line).

If you use clear command on Ubuntu with GNOME Terminal, it will clear the screen and you won’t be able to see what else you had on the screen previously.

In many other terminal emulators or Putty, it may just clear the screen for one page. If you scroll with mouse or PageUp and PageDown keys, you can still access the old screen outputs.

Frankly, it depends on your need. If you suddenly realize that you need to refer to the output of a previously run command, perhaps having that option available will be helpful.

Other ways to clear terminal screen in Linux

Clear Terminal Screen Linux

Clear command is not the only way to clear the terminal screen.

You can use Ctrl+L keyboard shortcut in Linux to clear the screen. It works in most terminal emulators.

If you use Ctrl+L and clear command in GNOME terminal (default in Ubuntu), you’ll notice the difference between their impact. Ctrl+L moves the screen one page down giving the illusion of a clean screen but you can still access the command output history by scrolling up.

Some other terminal emulators have this keyboard shortcut set at Ctrl+Shift+K.

You can also use reset command for clearing the terminal screen. Actually, this command performs a complete terminal re-initialization. It could take a bit longer than clear command, though.

There are a couple of other complicated ways to clear the screen when you want to clear the screen completely. But since the command is a bit complicated, it’s better to use it as alias in Linux:

Читайте также:  Linux range of use

You can add this alias to your bash profile so that it is available as command.

I know this was a pretty basic topic and most Linux users probably already knew it but it doesn’t harm in covering the elementary topics for the new Linux users. Isn’t it?

Got some secretive tip on clearing terminal screen? Why not share it with us?

Источник

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.

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:

$ echo "Hello, World!" $ cat /etc/os-release

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 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.

Читайте также:  Разметка дисков linux gparted

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

Источник

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

Linux Terminal Clear

Иногда бывает нужно очистить окно терминала от текста, чтобы начать работу, так сказать, с чистого листа. Рассмотрим 5 различных способов очистить терминал.

Команда clear

Самая простая для запоминания команда — команда clear.

Команда clear очищает окно терминала. На самом деле вывод предыдущих команд в терминале никуда не удаляется, просто строка ввода команд перемещается на первую строку терминала, а под ней вы получаете чистое пространство. (См. ниже, как удалить предыдущий текст в терминале.)

Команда reset

Команда reset предназначена для того, чтобы вернуть терминал в первоначальное состояние.

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

Сочетание клавиш Ctrl+L

Один из самых быстрых и простых способов очистить терминал — это нажать сочетание клавиш Ctrl+L .

Действие Ctrl+L аналогично выполнению команды clear.

clear && clear

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

printf «\033c»

Если выполнить в терминале команду printf «\033c», то окно терминала очистится.

Код 033 (восьмеричная система счисления) соответствует ASCII коду Esc-последовательности. Ввод Esc-последовательности+c в терминале выполняет сброс настроек терминал в первоначальное состояние (подобно команде reset).

Источник

How to Clear Terminal in Linux

The clear command is the go-to tool for clearing the terminal screen in Linux. Despite its effectiveness, clear does not reinitialize the terminal, which is sometimes necessary. Some alternative methods provide users with that option as well.

Read this tutorial to learn how to clear the terminal in Linux using different methods.

How to Clear Terminal in Linux <Clear Screen in Linux data-lazy-src=

The command deletes everything, including the scrollback buffer. To keep the scrollback buffer, use clear with the -x argument:

clear -x terminal output before

The clear -x command clears the terminal, but previous output is still available. Scroll up or use the PgUp button:

clear -x terminal output after

However, in some terminal emulators, clear without arguments doesn’t delete previous output but shifts it upwards (same as clear -x in GNU). In that case, accessing earlier output is possible with the PgUp key.

Additionally, the clear command does not reset the terminal. The shell state remains the same as before.

Clear Terminal via reset Command

Unlike clear , the reset command reinitializes the terminal and restores settings to default. The reinitialization process covers tab extensions, turns off echo and raw modes, and turns on newline translation.

Читайте также:  Linux драйвера принтер samsung scx

The command resets a terminal that is in an abnormal state and reinitializes the command line:

reset terminal output before

Executing reset takes a few moments to complete while clear shows effect instantly.

Clear Terminal via Ctrl+L / Ctrl+Shift+K Shortcut

Keyboard shortcuts also work for clearing the terminal, depending on the terminal emulator.

In GNOME, the Ctrl + l shortcut has the same effect as clear -x. The shortcut clears the terminal while leaving the scrollback buffer:

ctrl + l and new command terminal output

Typing in a new command, like whoami, is done on a clear screen. Still, users can access command output history with PgUp or by scrolling up:

ctrl + l terminal output

An alternative in some terminal emulators is Ctrl + Shift + K . The command provides the same output as Ctrl + L .

Clear Terminal via alias Command

Alternative methods for clearing the terminal are also more complicated. For instance, the \033 is the ASCII escape character used to start terminal control sequences. When followed by c , the command clears the terminal.

printf 33c terminal output

The command clears the terminal screen, including the scrollback buffer. To avoid typing numbers, create an alias for the command. For instance, set x as an alias for printf «\033c» with:

alias terminal output

Once the alias is created, running x results in a clear terminal screen.

Now you know how to clear the terminal screen using a few different methods. Next, check out the ultimate guide of all Linux commands everyone should know.

Источник

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

Оцените статью
Adblock
detector