Как удалить history linux

How do I clear the terminal History?

I am using Linux Mint 17.1 Rebecca for about 2 days and accidentally typed my password into the terminal which is now displayed in the history list of commands I have previously typed. I want to clear the terminal history completely. I have tried using the following commands in the terminal which I thought would clear the history forever but they do not:

history -c reset tput reset 

The above commands «will» clear the history from the terminal but when I exit and bring up a new one all my previous history is still there and can all be listed again using the — history command and also by pressing the UP arrow on my keyboard. I do not want this to happen until I have totally cleared my history, then I want to continue using it. How can I clear my terminal history completely — forever and start fresh? Please Note: I do not want to exit the terminal without saving history just clear it forever in this one instance.

@jasonwryan That alone wouldn’t solve the problem since the sed command would end up in the shell history.

I tried using the code from @jasonwryan but I got: sed: -e expression #1, char 0: no previous regular expression which I think I know why and that lead me to come up with this from a search and some messing around: cat /dev/null > ~/.bash_history && history -c && exit

7 Answers 7

reset or tput reset only does things to the terminal. The history is entirely managed by the shell, which remains unaffected.

history -c clears your history in the current shell. That’s enough (but overkill) if you’ve just typed your password and haven’t exited that shell or saved its history explicitly.

When you exit bash, the history is saved to the history file, which by default is .bash_history in your home directory. More precisely, the history created during the current session is appended to the file; entries that are already present are unaffected. To overwrite the history file with the current shell’s history, run history -w .

Instead of removing all your history entries, you can open .bash_history in an editor and remove the lines you don’t want to keep. You can also do that inside bash, less conveniently, by using history to display all the entries, then history -d to delete the entries you don’t want, and finally history -w to save.

Note that if you have multiple running bash instances that have read the password, each of them might save it again. Before definitively purging the password from the history file, make sure that it is purged from all running shell instances.

Читайте также:  Kali linux ошибка 0x8007019e

Note that even after you’ve edited the history file, it’s possible that your password is still present somewhere on the disk from an earlier version of the file. It can’t be retrieved through the filesystem anymore, but it might still be possible (but probably not easy) to find it by accessing the disk directly. If you use this password elsewhere and your disk gets stolen (or someone gets access to the disk), this could be a problem.

Источник

История команд 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:

На самом деле работать с историей еще более просто с помощью оболочки, возможно, вы уже используете многие ее функции, но о некоторых точно не знаете. Рассмотрим их:

Чтобы показать предыдущую команду просто нажмите стрелку вверх, так можно просмотреть список раньше выполненных команд.

Вы можете выполнить последнюю команду просто набрав «!!». Также можно выполнить одну из предыдущих команд указав ее номер «!-2»

Чтобы выполнить поиск по истории прямо во время ввода нажмите Ctrl+R и начните вводить начало команды.

Если вы знаете, что нужная команда была последней, которая начиналась на определенные символы, например, l, то вы можете ее выполнить, дописав «!l»:

Если нужная команда последняя содержала определенное слово, например, tmp, то вы можете ее найти, использовав «!?tmp»:

Если вы не хотите, чтобы выполняемая команда сохранилась в истории просто поставьте перед ней пробел.

Читайте также:  Синхронизировать время linux команда

Таким образом, вы можете очень быстро отыскать нужную команду, если помните как она была написана. История команд bash хранит очень много команд и этого вполне достаточно для комфортной работы.

Настройка истории Linux

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

export HISTTIMEFORMAT=’%F %T ‘
$ history

Для форматирования можно использовать такие модификаторы:

Вы можете указать какие команды не стоит отображать, например, не будем выводить ls -l, pwd и date:

export HISTIGNORE=’ls -l:pwd:date:’

Также можно отключить вывод одинаковых команд:

Существует два флага, ignoredups и ignorespace. Второй указывает, что нужно игнорировать команды, начинающиеся с пробела. Если вы хотите установить оба значения, используйте флаг ignoreboth. Используйте переменную HISTSIZE, чтобы установить размер истории:

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

export PROMPT_COMMAND=»$history -a; history -c; history -r;»

Для тестирования работы вы можете набирать эти команды прямо в терминале и сразу видеть результат, но для сохранения добавьте нужные строки в ваш ~/.bashrc. Например:

export PROMPT_COMMAND=»$history -a; history -c; history -r;»
$ export HISTCONTROL=ignoredups
$ export HISTTIMEFORMAT=’%F %T ‘

Готово, теперь осталось сохранить изменения и перезапустить ваши терминалы. Теперь ваша история будет выводить дату, игнорировать дубли и синхронизироваться между терминалами.

Выводы

В этой статье мы рассмотрели что такое история команд linux, как с ней работать, как применяется команда history linux и какие настройки можно использовать для более комфортной работы. Если у вас остались вопросы, спрашивайте в комментариях!

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

Источник

How to clear bash history completely?

I want to clear all previous commands from the history of my server. I used history -c and it seems all things are cleared but when I ssh to the server, all the commands are still there. How can I clear them permanently?

9 Answers 9

The file ~/.bash_history holds the history.

To clear the bash history completely on the server, open terminal and type

cat /dev/null > ~/.bash_history 

Other alternate way is to link ~/.bash_history to /dev/null

However,

One annoying side-effect is that the history entries has a copy in the memory and it will flush back to the file when you log out.

To workaround this, use the following command (worked for me):

cat /dev/null > ~/.bash_history && history -c && exit 

you can also put above command in .bashrc & .bash_logout . what it mean when you login u will have clear history & when you logout out your history will be cleared

I tried to do it on a raspberry box while connected via SSH. I added the above command ( cat /dev/null > ~/.bash_history && history -c && exit ) to both .bashrc & .bash_logout as suggested by @Qasim . Now as soon as I connect via SSH the remote host closes the connection (after printing the motd) . Help :/

Читайте также:  Невозможно запустить принтер проверьте конфигурацию принтера linux

Goes to show what happens when you blindly do things without reading properly and without understanding the processing and data flow. It also shows the pitfalls of bad communication. What devav2 did was run it one time, and what Qasim should have written is to remove the exit command before adding it in login script.

In every open bash shell (you may have multiple terminals open):

Why: As noted above, history -c empties the file ~/.bash_history . It is important to note that bash shell does not immediately flush history to the bash_history file. So, it is important to (1) flush the history to the file, and (2) clear the history, in all terminals. That’s what the commands above do.

For some reason this does not work on Ubuntu 14.04, probably others. It should but it doesn’t. If you issue the command «history -cw» you can confirm with the up arrow that the history isn’t there anymore, but if you start another terminal window (in Unity desktop) with shift + click on the terminal icon (I have it pinned in the launcher) the commands history are back, no matters how many times you do «history -cw». «cat /dev/null > ~/.bash_history» is the only way that worked for me.

It’s history -c and then history -w, you first clear the history then write the changes. This is easily confirmed by closing the terminal and opening it again, with -w first the commands are there again, with -w last history is effectively cleared.

execute the following commands to clear history forever

This answer would be even more helpful if it explained what these flags do (and therefore why/when they’re the right commands to use).

There’s another much simpler one: running history -c on the terminal prompt and gone are all entries in the bash_history file.

If you read the OP’s question you would know that using history -c is the exact method that led to this question.

Clear the current shell’s history:

When you log out, your current shell’s history is appended to ~/.bash_history, which is a cache of previous shells’ histories, to a maximum number (see HISTFILESIZE in «man bash»).

If you want to remove the history altogether, then you essentially have to empty out ~/.bash_history which many of the above entries have suggested. Such as:

This clears the current shell’s history and then forces the current shell’s history (empty) to overwrite ~/.bash_history. or to be more accurate, it forces it to overwrite HISTFILE (which defaults to ~/.bash_history).

Источник

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