Очистить ком строку linux

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?

To clarify the MacOS commands: cmd.K — clear terminal, can’t scroll up || ctrl.L — clear screen, scroll up for history || multiple ctrl.L — clear multiple screens. Can see the empty prompt for each clear, and will be able to see history prior to the number of clears

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:

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

Personally I don’t mind that something is left «up» along the scroller when I hit ^L . I don’t see it (that’s what I want!), I don’t feel it, and if suddenly I would need to restore what was there — no problem. reset in contrast is much harder tool — I’ll use it when something went wrong with the terminal — like, when weird escape sequences accidentally ruined the display altogether.

@ulidtko: it does matter when you run consecutive sessions of programs with tons of output. If you scroll back it’s easy to get confused about which execution printed something. I know perfectly well that more sophisticated solutions could be used in these cases, but nonetheless it’s a scenario that comes about pretty often in quick & dirty debugging sessions.

There’s also tput reset which visibly does the same thing, but completes instantaneously (whereas reset can take up to about 2 seconds before the prompt reappears).

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.

Great find! And for those who want the Bash-style reset on mac: nano ~/.bashrc and add alias reset=»clear && printf ‘\e[3J'»

be careful aliasing reset — it does more than just clear the terminal. for example, if you accidentally print a binary file with random garbage that corrupts the terminal (e.g. disables echoing of typed characters), reset can usually fix that. of course aliasing is fine as long as you know how to \override an alias-shadowed command.

Читайте также:  Linux grub восстановление загрузки

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

+1. I always have the Menubar hidden; so even after years and years of using gnome, I never thought to look for this. Thanks 🙂

“Reset” do nothing for me, and “Reset and Clear” clear everything but does not re‑display the prompt. None of these menu entries behave like the “reset” command from a terminal.

As @Hibou57 said, my keyboard shortcut for «Reset» doesn’t seem to do anything. Is this functionality broken in 14.04?

@Hibou57 «Reset and Clear» isn’t expected to re-display the prompt, but if you hit Enter afterwards it should re-display the prompt. Does that work for you?

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

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.

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

I got the scroll-back clearing command from here.

This has the same effect as launching a new terminal.

When using putty, after running reset , I can still scroll up and see previous stuff. Is this an issue with PuTTY rather than reset ?

@Bira No, reset doesn’t clear the scrollback on macOS 10.14 Mojave. You could try seq 100; reset to see scrollback still there. On macOS terminal, Cmd+K can clear screen and scrollback.

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.

Additionally, in my .bashrc I have a binding like this:

Now I press ctrl t all the time.

Do you know how could a mapping be created using the Windows key ? This snippet is really great, works exactly like Command-K on mac. Thank you.

@Niloct you can see if the terminal supports it with xev (just type xev in a terminal inside an x-session). From what I could tell, urxvt doesn’t support it; while I didn’t try in a tty, I am confident it would not be supported. I also doubt xterm or gnome-terminal would support this. It’s tricky with ansi-escapes. Cheers and sorry for late reply.

Читайте также:  Клиент сервер сокеты linux

Источник

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

В определенных случаях после запуска терминала в ОС Linux можно увидеть, что он переполнен командами и выводами, которые были созданы благодаря использованию этих команд. У пользователей возникает вопрос: «Каким образом можно очистить терминал, чтобы продолжить их ввод с вершины списка?». Для очистки консоли Linux потребуется ввести определенные команды, которые будут описаны ниже.

Утилита «clear»

clear

Данная утилита является самой популярной. Для большинства современных пользователей полученного результата будет вполне достаточно. Команду «clear» потребуется ввести в нижней части терминала. После нажатия кнопки ввода экран очищается практически моментально. Нужно заметить, что после использования этой утилиты могут возникнуть проблемы. Предположим, что пользователю необходимо провести мониторинг сетевой активности. Это делается для того, чтобы выявить попытки взлома. Анализ осуществляется путем прокручивания колесиком мышки. Если пользователь выполнил очистку терминала от выводов с помощью «clear», сложно определить, где начинается и заканчивается результат выполнения. Существенно увеличивается риск совершения ошибки во время анализа имеющихся данных.

Утилита «reset»

reset

Эту фразу также нужно ввести в нижней части экрана, перед словом «reset» . Терминал будет очищен моментально. После тщательного изучения страницы мануала становится понятно, что команда «reset» реинициализирует терминал. Она перезапускает его. Этого не способна сделать утилита «clear», так как она лишь отодвигает возникающие выводы на экране.

Стоит отметить, что «reset» не способна повлиять на состояние внешней оболочки. Она останется неизменной.

Команда printf «\033c»

printf

Другой способ очистки командной строки – введение на экране фразы printf «\033c» и нажатие кнопки «enter». После проведения этой процедуры исключена вероятность повторной инициализации экрана.

Применение горячих клавиш

Для упрощения очистки экрана в ОС Linux предусмотрено использование горячих клавиш. Пользователю потребуется одновременно нажать Ctrl + L. Этот метод даст возможность получить такой же результат, как при использовании утилит clear и reset.

Особенности очистки различных терминалов Linux

  • KDE. Иное его название – Konsole. Здесь весьма удобно использовать «# clear && echo -en «\ e [3J»». Очистить экран можно и с псевдонимом «alias cls», но лучше использовать сочетание горячих клавиш Ctrl + Shift + K.
  • GNOME и Ubuntu 18.04. У них аналогичные требования по введению команд. Для удаления ненужной информации на экране рекомендуется одновременно ввести горячие клавиши Shift + Ctrl + Alt + C.

Источник

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:

Читайте также:  Astra linux руководство администратора безопасности

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.

Источник

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

Источник

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