- Как очистить историю команд в Linux
- Почему мы должны удалить историю командной строки Linux?
- Удаление истории командной строки Linux
- История команд Linux
- История команд Linux
- Настройка истории Linux
- Выводы
- How To Clear Command Line History In Linux
- Why should we clear Command line history?
- Why shouldn’t we clear Command line history?
- Clear Command line history in Linux
- 1. Clear entire Command line history using history command
- 2. Avoid saving commands in history list by inserting a blank space before each command
- 3. Clear or delete specific commands from history
- 4. Clear Command line history automatically at logout
- 5. Delete Command line history permanently
- Conclusion
Как очистить историю команд в Linux
Главное меню » Ubuntu » Как очистить историю команд в Linux
Почему мы должны удалить историю командной строки Linux?
В большинстве случаев мы не хотим раскрывать историю терминалов других пользователей вашей системы Linux. Например, если вы проводите занятия со своими учениками на лабораторном компьютере, и, возможно, вы научили их некоторым вредоносным командам, которые не рекомендуется использовать в нашей системе. Но большинство студентов не имеют представления о побочных эффектах этих важных команд. Любопытный студент может поискать в истории командной строки и протестировать ее, чтобы проверить работу каждой команды. Это может привести к сбою вашей системы много раз. Однако вы можете быстро отремонтировать или переустановить свою систему. Но это не очень хорошая практика. Итак, в этом случае мы хотим очистить историю командной строки после работы с ней. Особенно, если у вас есть общий доступ со своими друзьями или коллегами. Мы только что разработали это на простом примере; могут возникнуть другие проблемы, из-за которых вы захотите очистить историю командной строки Linux. В этой статье мы покажем вам, как можно очистить историю командной строки в системе Linux.
В этой статье мы выполнили все команды терминального приложения в Ubuntu 20.04. Следовательно, необходимо открыть окно терминала в вашей системе. Щелкните «Действия», расположенный в левом углу на рабочем столе вашей системы, а затем, используя панель поиска приложения, вы выполните поиск по ключевому слову «терминал». После завершения поиска щелкните значок терминала и запустите его.
Удаление истории командной строки Linux
Если вы хотите просмотреть историю своей команды терминала, введите в терминале следующую команду:
Обычно история командной строки сохраняется в файле с именем «bash_history». Этот файл вы можете найти в домашнем каталоге конкретного пользователя /home/username/.bash_history. Выполните приведенную ниже команду, чтобы найти файл bash_history:
Источник
История команд Linux
В терминале Linux, кроме всего прочего, есть одна замечательная вещь. Это история команд Linux. Все команды, которые вы вводите во время работы сохраняются и вы можете найти и посмотреть их в любой момент. Также можете вернуться на несколько команд чтобы не набирать недавно выполненную команду заново.
В этой небольшой статье мы рассмотрим как пользоваться историей команд Linux, как ее настроить, а также рассмотрим полезные приемы, которые могут помочь вам в работе.
История команд Linux
Большинство задач, связанных с историей команд, мы будем выполнять либо с помощью команды history, либо с помощью оболочки. В истории хранится последняя 1000 команд, которые вы выполняли. Чтобы посмотреть всю историю для этого терминала просто запустите команду history без параметров:
Для дополнительных действий с историей вам могут понадобиться опции. Команда history linux имеет очень простой синтаксис:
$ history опции файл
В качестве файла можно указать файл истории. По умолчанию история для текущего пользователя хранится в файле
/.history, но вы можете задать, например, файл другого пользователя. А теперь рассмотрим опции:
- -c — очистить историю;
- -d — удалить определенную строку из истории;
- -a — добавить новую команду в историю;
- -n — скопировать команды из файла истории в текущий список;
- -w — перезаписать содержимое одного файла истории в другой, заменяя повторяющиеся вхождения.
Наиболее полезной для нас из всего этого будет опция -c, которая позволяет очистить историю команд linux:
Так вы можете посмотреть только последние 10 команд:
А с помощью опции -d удалить ненужное, например, удалить команду под номером 1007:
Если вы хотите выполнить поиск по истории bash, можно использовать фильтр grep. Например, найдем все команды zypper:
history | grep zypper
На самом деле работать с историей еще более просто с помощью оболочки, возможно, вы уже используете многие ее функции, но о некоторых точно не знаете. Рассмотрим их:
Чтобы показать предыдущую команду просто нажмите стрелку вверх, так можно просмотреть список раньше выполненных команд.
Вы можете выполнить последнюю команду просто набрав «!!». Также можно выполнить одну из предыдущих команд указав ее номер «!-2»
Чтобы выполнить поиск по истории прямо во время ввода нажмите Ctrl+R и начните вводить начало команды.
Если вы знаете, что нужная команда была последней, которая начиналась на определенные символы, например, l, то вы можете ее выполнить, дописав «!l»:
Если нужная команда последняя содержала определенное слово, например, tmp, то вы можете ее найти, использовав «!?tmp»:
Если вы не хотите, чтобы выполняемая команда сохранилась в истории просто поставьте перед ней пробел.
Таким образом, вы можете очень быстро отыскать нужную команду, если помните как она была написана. История команд bash хранит очень много команд и этого вполне достаточно для комфортной работы.
Настройка истории Linux
Linux — очень настраиваемая и гибкая система, поэтому настроить здесь можно все, в том числе и историю. По умолчанию выводится только номер команды, но вы можете выводить и ее дату. Для этого нужно экспортировать переменную HISTORYFORMAT вместе нужным форматом:
export HISTTIMEFORMAT=’%F %T ‘
$ history
Для форматирования можно использовать такие модификаторы:
- %d – день;
- %m – месяц;
- %y – год;
- %T – штамп времени;
- %F — штамп даты.
Вы можете указать какие команды не стоит отображать, например, не будем выводить ls -l, pwd и date:
export HISTIGNORE=’ls -l:pwd:date:’
Также можно отключить вывод одинаковых команд:
Существует два флага, ignoredups и ignorespace. Второй указывает, что нужно игнорировать команды, начинающиеся с пробела. Если вы хотите установить оба значения, используйте флаг ignoreboth. Используйте переменную HISTSIZE, чтобы установить размер истории:
По умолчанию история сохраняется для каждого терминала отдельно. Но если вы хотите чтобы все ваши команды немедленно синхронизировались между всеми терминалами, то это очень просто настроить. Добавьте такую переменную:
export PROMPT_COMMAND=»$
Для тестирования работы вы можете набирать эти команды прямо в терминале и сразу видеть результат, но для сохранения добавьте нужные строки в ваш
export PROMPT_COMMAND=»$
$ export HISTCONTROL=ignoredups
$ export HISTTIMEFORMAT=’%F %T ‘
Готово, теперь осталось сохранить изменения и перезапустить ваши терминалы. Теперь ваша история будет выводить дату, игнорировать дубли и синхронизироваться между терминалами.
Выводы
В этой статье мы рассмотрели что такое история команд linux, как с ней работать, как применяется команда history linux и какие настройки можно использовать для более комфортной работы. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
How To Clear Command Line History In Linux
In Bash, all the commands that you run in the Terminal are stored in a text file named in .bash_history in your home directory. We can use the history command to display a list of the commands entered since you started the session. For some reason, you may want to delete all or a specific command from the Bash history. In this brief guide, let us learn how to clear command line history in Linux with examples.
Before getting to the topic, first let us see why should we clear the command line history and why shouldn’t we do it in some cases.
Why should we clear Command line history?
There are chances that you don’t want to expose the Command line history of your Linux system. Say for example, if you are a Linux trainer/tutor, you might have taught some commands to your students in the Lab computer.
Those commands might be harmful and are not supposed to use. But the students may not fully aware of the consequences of such critical commands.
A curious student might search the command line history, and wonder what does those commands will do, and start to test them one by one. The result? He/she might inadvertently break the system.
Would you allow that? Of course, we can re-install or repair the system in couple minutes. However, it is completely unnecessary if you are bit careful. So, clearing Command line history from time to time, especially in a shared computer, is a good practice.
It is just an example. There could be many other reasons to clear Linux command line history.
Why shouldn’t we clear Command line history?
Clearing Command line history is a good practice, however you must not clear history in some cases. Say for example, you want to repeat a specific command often. Would you type the same command every time? That’s not necessary.
As I said earlier, the commands that you run on the Terminal will be retained in the
/.bash_history file. You can retrieve the previously executed commands by pressing the UP arrow in the keyboard.
When you hit the UP, the list of commands that you run recently will appear. Just keep hitting the UP arrow key until you find the command that you want to run. Once you find the command that you want to run, just hit ENTER to execute. That’s it. You don’t have to type the entire command every time.
Sometimes you can’t remember some lengthy and complex commands in a previous session. In such cases, you can use history command to retrieve the previously executed commands.
So if you already cleared the Bash history, you can access the previously entered commands. This is why you should decide whether you want to clear the command line history or not.
Without further ado, let us see how to clear command line history in Linux.
Clear Command line history in Linux
There are many ways to clear Command line history. Here I have listed five ways.
1. Clear entire Command line history using history command
As stated earlier, the history command will display the last executed commands.
To view the previously executed commands in Linux, run:
To clear the history, just run any one of the following commands:
The above commands will clear the command line history.
2. Avoid saving commands in history list by inserting a blank space before each command
Using this method, you can eliminate a specific command getting saved in the history list. Just put a blank space (Hit space bar from the keyboard) before any command. The command will not be recorded in history.
To do that, you must set HISTCONTROL environment variable’s value as “ignorespace” or “ignoreboth”.
Add the following line at the end:
Save and close the file. Run the following command to take effect the changes.
Or, simply log out and log back in to apply the changes.
To verify it, run a few commands. And put a blank space in-front of any command. I put a blank space in last command.
Here indicates a blank space.
Refer the following screenshot:
Put a blank space before a command to avoid saving it in history in Linux
Now, run the history command to view the recently executed commands:
Sample output:
clear Command line history in Linux
As you see in the above output, the «sudo ping ostechnix.com» command is not displayed in the history command output.
3. Clear or delete specific commands from history
Sometimes you might want to delete some particular commands from history list, instead of clearing the entire history.
Let me show you an example. I am going to run the following commands in the Terminal.
Then, display the history command output using command:
sample output:
As you see in the above output, the history command displays the last executed commands.
To clear or delete a particular command from the history, use -d flag with the command prefix number:
Here represents the line number of each command.
For example, to delete the «time» command with line number «5» from the history, run:
Now, display the command line history to see if the command is removed or not.
Sample output:
Clear or delete specific commands from history
As you see, the «time» command has been removed. Similarly, you can delete any command from the history list.
4. Clear Command line history automatically at logout
Instead of manually clearing history each time, you can automatically clear it at logout.
Add the following line:
Save and close the file. Now, the history will be cleared after you logout from the session.
5. Delete Command line history permanently
All of the above methods will only remove the commands from the active session i.e currently opened terminal. If you have multiple terminals running different commands, the history command will only delete the history from where you run this command. The commands from other terminals will still be available.
To remove all commands from Bash history in all sessions, you must remove the contents of .bash_history file. This file contains the list of commands that we run in the terminal. You can either clear this file manually each time or setup a cron job to clear it at regular intervals.
To manually clear the contents of this file, run:
Like I said, this will delete the entire history. The next time this file will start to record the history. You should run this command everyday to clear the contents of this file.
Alternatively, you can schedule this task at regular interval using cron jobs.
Add the following commands:
Save and exit file. The history will be automatically cleared at 8 pm everyday.
Recommended read:
Conclusion
In this tutorial, you have learned why should we clear the command line history, and why you shouldn’t do it in some cases. Also, you have learned the different ways to clear command line history in Linux. If you know any other method to do it, feel free to let us know in the comment section below.
Источник