Linux bash очистка экрана

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:

Читайте также:  Linux сколько осталось места диске

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.

Источник

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

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

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

  1. На мой взгляд, самый простой и самый быстрый способ очистки терминала — использование комбинации клавиш ctrl+L ( control+L для MacOS).
  2. Вторым широко известным способом очистки консоли является команда clear .
  3. На третьем месте по частоте использования в целях очистки терминала находится команда reset .
  4. Далее следуют несколько экзотические способы. Например, для очистки терминала можно ввести такую команду:

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

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

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

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

alias cls='clear && echo -en "\e[3J"' 
  1. В дистрибутивах с оболочкой GNOME (например, Ubuntu 18.04) можно самостоятельно назначить комбинацию клавиш, которая будет отвечать за очистку терминала, например:

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

Read more

© Copyright 2023 Yevhen Lebid

Источник

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.

Читайте также:  Linux сколько оперативной памяти установлено

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:

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 команды для очистки экрана терминала в Linux

Как и любая другая операционная система, Linux также поддерживает богатый графический интерфейс пользователя ( GUI ). Фактически, он поддерживает множество графических окружений рабочего стола, таких как GNOME , KDE , Cinnamon, и список можно продолжить.

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

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

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

Очистка терминала Linux с помощью команды clear

Команда clear является одной из наиболее часто используемых команд для очистки терминала Linux. Эта команда просто очищает экран терминала, включая буферы обратной прокрутки.

Чтобы понять использование команды, давайте выполним несколько команд в терминале:

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

Для очистки экрана просто выполните команду clear без какого-либо аргумента:

Очистка экрана терминала Linux с помощью сочетания клавиш CTRL + L

Подобным образом мы можем использовать сочетание клавиш Ctrl + L для очистки экрана терминала. Однако этот метод не очищает буферы обратной прокрутки.

Чтобы проиллюстрировать это, сначала очистите экран терминала с помощью сочетания клавиш Ctrl + L , а затем прокрутите экран вверх с помощью мыши:

В данном примере мы можем увидеть предыдущий вывод, прокрутив терминал вверх.

Очистка терминала Linux с помощью команды reset

Дополнительно, мы также можем использовать команду reset для очистки экрана терминала. Как и команда clear, команда reset также очищает буферы обратной прокрутки.

Команда reset повторно инициализирует терминал, поэтому она занимает больше времени по сравнению с командой clear.

Очистка терминала с помощью кода Escape

Для очистки терминала мы можем использовать код c . Давайте разберемся на простом примере.

В bash для обозначения символа ESC мы можем использовать escape-последовательность e . Таким образом, чтобы очистить экран терминала, мы можем использовать строку ec с командой printf, как показано ниже:

Читайте также:  Mysql delete user linux

Аналогичным образом мы можем использовать восьмеричное число 33 для представления символа ESC . Поэтому для очистки терминала мы можем использовать строку 33c с командой printf:

В дополнение к этому, шестнадцатеричное число x1B представляет символ ESC . Следовательно, мы можем использовать его для очистки экрана:

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

Источник

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.

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.

Источник

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