Linux history удалить несколько строк

How to remove a single line from history?

I’m working in Mac OSX, so I guess I’m using bash. Sometimes I enter something that I don’t want to be remembered in the history. How do I remove it?

history -d didn’t work for me, so just deleted the desired line and the one preceding it (that should start with # ) from ~/.bash_history .

From macOS Catalina on, the standard shell is zsh and not bash and the history command works differently, so history -d will not work. @toraritte answer becomes then: type vim .zsh_history and delete typing d once on the line you need to delete. To save and quit then type 😡 and hit Enter .

13 Answers 13

Preventative measures

If you want to run a command without saving it in history, prepend it with an extra space

prompt$ echo saved prompt$ echo not saved \ > # ^ extra space 

For this to work you need either ignorespace or ignoreboth in HISTCONTROL . For example, run

To make this setting persistent, put it in your .bashrc .

Post-mortem clean-up

If you’ve already run the command, and want to remove it from history, first use

to display the list of commands in your history. Find the number next to the one you want to delete (e.g. 1234) and run

Additionally, if the line you want to delete has already been written to your $HISTFILE (which typically happens when you end a session by default), you will need to write back to $HISTFILE, or the line will reappear when you open a new session:

@BSeven Yes, all bash settings are stored in RAM while the shell is running. The rc files are only for storing persistent settings for the next time the shell starts.

@jw013 I set PROMPT_COMMAND to history -a , in that case it is already written to the history file, rather than on exit under normal configuration. Specifically: mywiki.wooledge.org/BashFAQ/088

@Gauthier because history is also a bash builtin. type history reveals that. Use man bash-builtins to find the man page for it.

@DavidSawyer I see, this answer would make sense to someone familiar with history . I’m not familiar with it, as you can maybe tell.

I have this in my ~/.bashrc , which makes the command $ forget delete the previous command from history

That seems a little complicated. Wouldn’t history -d $( history | tail -n 1 | cut -f 1 -d » » ) be simpler?

history | tail -n1 is the history command itself, so deleting that number gets the wrong entry. However, history -d $( history | awk ‘END‘ ) combines the line select, field select, and subtraction.

You always can edit and remove entries from ~/.bash_history , useful when you want to remove either one entry or more than one entry

This may needlessly remove more than necessary, or may possibly not remove anything, depending on how the shell is configured.

Zsh on Mac

If you are using Zsh, history -d linenumber doesn’t work to delete a specific line number in the command line history. However you can edit the history file. Close and reopen your terminal and edit the history like so:

Читайте также:  Kali linux install ftp

If you want to forget the entire bash session, you can kill the current bash process. Since the variable $$ hold the pid of the current shell, you can do:

@Kusalananda unless you have taken special steps to write to the $HISTFILE immediately, this should work. The ONLY think I have taken into account is the $HISTFILE . What experience have you had (with my proposal) that causes you concern?

If the thing that the user entered was in a previous session, killing the current shell would not remove that single thing from the history file. Also, I’m on systems where the admins have changed the default setup so that commands are written to the history file after every given command. We know nothing about the current user’s setup.

@Kusalananda your statement is true. However, I would hope that no one would ever try to kill the current process trying to affect the result of a past completed process. That’s just illogical to expect. But it does suggest a slightly different phrasing to your original comment that would have avoided the confusion. «This does not affect the history that was written to $HISTFILE in previous sessions.» In other words, «this concept is only good for preventing the situation, not correcting it.» Thanks for clarifying, friend.

Well, it wouldn’t affect the history written to $HISTFILE in the current session either, so I really don’t see how that comment could be misinterpreted. The only thing you have to add to your answer is the assumptions under which the given solution solves the problem. There is really only one assumption, namely that the command that should be removed from the history hasn’t yet been written to $HISTFILE . Then you may want to elaborate under what conditions the command would have been written to $HISTFILE .

Источник

История команд Linux

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

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

История команд Linux

Большинство задач, связанных с историей команд, мы будем выполнять либо с помощью команды history, либо с помощью оболочки. В истории хранится последняя 1000 команд, которые вы выполняли. Чтобы посмотреть всю историю для этого терминала просто запустите команду history без параметров:

Для дополнительных действий с историей вам могут понадобиться опции. Команда history linux имеет очень простой синтаксис:

$ history опции файл

В качестве файла можно указать файл истории. По умолчанию история для текущего пользователя хранится в файле ~/.history, но вы можете задать, например, файл другого пользователя. А теперь рассмотрим опции:

  • -c — очистить историю;
  • -d — удалить определенную строку из истории;
  • -a — добавить новую команду в историю;
  • -n — скопировать команды из файла истории в текущий список;
  • -w — перезаписать содержимое одного файла истории в другой, заменяя повторяющиеся вхождения.
Читайте также:  Do while in shell linux

Наиболее полезной для нас из всего этого будет опция -c, которая позволяет очистить историю команд linux:

Так вы можете посмотреть только последние 10 команд:

А с помощью опции -d удалить ненужное, например, удалить команду под номером 1007:

Если вы хотите выполнить поиск по истории bash, можно использовать фильтр grep. Например, найдем все команды zypper:

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

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

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

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

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

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

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

Таким образом, вы можете очень быстро отыскать нужную команду, если помните как она была написана. История команд 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 do I remove the last 5 lines in bash history?

How can I remove the last 5 lines in bash history? So that when I reload the Ubuntu server, or restart it they’re not there at all? history -c only removes it from current session, but when I re-login I see the commands again, I want to clear the last 5. I’ve run:

 489 cd .. 490 cd .zshrc 491 cat .zshrc 

Then i close terminal and reopen it and i still see line 489 it was only deleted for that current session, how do I delete it permentantly from all sessions going forward?

Читайте также:  Linux хостинг как сделать

Is the history file not just a simple .txt file that can be edited?. Sorry in Windows right now and never actually tried.

5 Answers 5

You can achieve removal from the history file using the command line in two steps:

Typing history -d deletes a specified line from the history in memory. Typing history -w writes the current in-memory history to the ~/.bash_history file. The two steps together remove the line permanently from the in-memory history and from the .bash_history file as well.

This is a lot closer, so I run history -wd 493 for example, and it works to delete it for good, however, then in history I have a bunch of history -wd’s etc. so it’s counterintuitive, how can i clear e.g. the last 5 commands all in one shot that would be best, and then the actual command i used to clear them itself.

@EODCraftStaff Type man and the name of the command manual you want to see. In this case: man history .

Use a space before your history delete command and it wont go to your history after it removes content from the history. Alternately, kill -s 9 $$ when you’re done.

I think you need to try this its very easy & simple.

    How to delete history without any trace

history -d $((HISTCMD-1)) && history -d NO_of_History_you_want_to_delete 
history -d $((HISTCMD-1)) && type_your_command_here_and_execute 

(2.) doesn’t answer the question and it would be far easier to prepend the traceless command with a space character to omit its addition to the history.

(1.) is both an excellent and elegant solution. I’m not sure how adding a space prevents it from being added to the history, David

@theking2 For some systems pre-pending a space tells bash not to write the command to the history https://stackoverflow.com/questions/6475524.

There are different ways to accomplish this task, but lets clarify something before going further.

There is a file named: ~/.bash_history , which contains your older terminal sessions history, whenever you close your terminal, your history will be saved there.

At the same time the history of your old sessions along with current session is temporary accessible by history commands until you close the terminal which then will be saved into ~/.bash_history file.

So if you remove 5 lines at the end of ~/.bash_history , then closing terminal will cause your current command to be accessible at next sessions.

So if I do a wc on .bash_history:

Most of the time I’ll get a smaller number than of history | wc -l .

If you want to remove the last 5 line of the file, you can use this command:

for i in ; do sed -i '$d' .bash_history; done; 

And if you want to keep all history except last 5 command issued in current session run:

history | awk '< print $2 >' | head -n -5 > .bash_history 

Don’t forget to run history -c too.

Источник

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