Command from history linux

How to delete a single command from history on a Linux/Unix Bash shell

Table of contents

How do I view history with line number?

Simply type the history command:
$ history
Sample outputs:

Fig.01: Bash history command with line number on a Linux, OS X, and Unix

By default, history is stored in

/.bash_history file. However, the bash variable named $HISTFILE defines the file’s name in which command history is saved. If unset, the command history is not saved when a shell exits. Use the printf command/echo command to display the current settings:

How to delete a single command number 1013 from history in Linux

Verify it:
$ history

Remove the bash history entry at position OFFSET. Negative offsets count back from the end of the history list.

How do I delete all the history?

Want to remove all bash history? Try the following syntax:
$ history -c
Add above command to your

/.bash_logout file to clean when you logout:
$ cat /dev/null >

/.bash_history && history -c
The -c passed to the history command to clear the history list by deleting all of the entries $.

Tip: Control bash history like a pro

First, you can increase your bash history size by appending the following config option in

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Save and close the file.

Where to find more information about history command?

Read bash man page by typing the following man command:
$ man bash
Another option is to type the following help command:
$ help history
Here is what I see on Bash version 5.0.17:

Conclusion

In this quick tutorial, you learned to remove a single command from bash history running on a Linux, macOS, *BSD, or Unix-like systems. I would suggest reading the bash man page for more information here.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Tutorial requirements
Requirements Bash on Linux/Unix
Root privileges No
Difficulty Easy
Est. reading time 4 mintues
Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Occasionally I will mistakenly paste a bunch of garbage on the command line, such as as some text that had been selected earlier. Sometimes this happens when copy/paste is not working correctly, or maybe I just made a mistake.

As I don’t want that junk in the command history, I will do the following:

history -w myhist
Edit myhist to remove unwanted lines
history -r myhist

Another use of this sequence of commands is to prime the history from a particular history file for a particular project. This saves a fair amount of typing at times.

I forgot to mention for those that may not be familiar with it, this is in the bash shell.

Hi,
Thanks a lot…
we can change history file format and add time of executed commands by HISTTIMEFORMAT variable….

example:
HISTTIMEFORMAT=”%D %T”

Yes. You can change the the file format.

I wonder. How do you intercept dangerous parameters on certain commands from ever being run. For instance could you block “rm -rf” ?

You may wan to try https://github.com/dvorka/hstr which brings easy history management (apart to suggest-box style navigation).

This doesn’t work on macOS 10.12.x

You may be using ZShell instead of Bash shell.

Источник

Команда History в Linux (История Bash)

Если вы проводите много времени в командной строке, просмотр истории команд, которые вы ранее запускали, может быть полезной функцией, которая может упростить вашу повседневную работу и повысить вашу производительность.

В этой статье мы поговорим о команде history , которая позволяет просматривать список ранее выполненных команд, выполнять поиск по списку и управлять файлом истории.

Использование команды history и расширений истории

history — это встроенная оболочка, и ее поведение может немного отличаться от оболочки к оболочке. Мы рассмотрим встроенную в Bash версию history .

В простейшей форме при вызове без какой-либо опции или аргумента команда history отображает весь список истории с номерами строк.

При вводе !n выполняется n-я команда из списка истории, а !-n команда возвращается на n строк. В следующем примере мы выполняем команду в строке 467 :

Другой способ выполнить команду — использовать расширение !word . word относится к самой последней команде, начинающейся с слова.

Обычно в history отображается много строк вывода, которые не помещаются на экране. Чтобы просмотреть вывод по одной странице за раз, направьте его в программу пейджера, например, команду more или less :

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

Используйте клавиши со стрелками up и down для перемещения по записям в списке. Когда отобразится искомая команда, нажмите Enter чтобы выполнить ее.

Типа !! для выполнения предыдущей команды:

Это особенно полезно, когда вы забываете привязать команду к sudo и вместо повторного ввода команды можете ввести:

!-1 совпадает с !! и выполняет последнюю команду из списка истории !-2 секунды до последней и так далее.

^word1^word2^ позволяет повторно запустить последнюю команду, заменив «word1» на «word2». Если вы случайно набрали sduo command вместо команды sudo command вы можете повторить команду, используя правильное слово:

Используйте команду grep для фильтрации вывода. Например, чтобы просмотреть все команды, включая «nano», вы должны выполнить:

Теперь, если вы хотите повторно запустить команду nano setup.py просто введите:

Другой способ поиска в истории команд — нажать Ctrl-R . Приглашение изменится на следующее, и вы сможете начать поиск ранее выполненной команды.

Оболочка отобразит соответствующую строку. Чтобы перейти к следующему подходящему предложению, снова нажмите Ctrl-R .

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

Сохранение списка истории

По умолчанию при запуске нового сеанса Bash читает список истории из файла .bash_history . Список команд, которые выполняются в текущем сеансе, хранятся в памяти и сохраняются в файле при закрытии сеанса.

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

Параметр -a позволяет сохранить список истории текущего сеанса в файл .bash_history :

Параметр -w записывает полный список истории в файл истории.

История очистки

Команда history позволяет очистить полный список истории или удалить определенные части.

Чтобы очистить список истории, используйте параметр -c :

Чтобы удалить определенную строку или строки между начальной и конечной позициями из списка истории, используйте параметр -d .

Например, чтобы удалить строки между 365 и 375 (включая эти строки), вы должны ввести:

Если вы укажете только одно число для опции -d , команда удалит данную строку.

Когда используется отрицательное целое число, строки отсчитываются от конца списка истории.

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

Изменение поведения в истории

Поведение истории Bash можно определить с помощью нескольких различных переменных среды . При изменении поведения истории установите переменные в

/.bashrc или любом другом файле конфигурации, который загружается при входе пользователя в систему.

По умолчанию Bash сохраняет 500 строк в списке истории команд. Переменная HISTSIZE позволяет вам изменять это значение. Чтобы установить значение 10000, добавьте в файл .bashrc следующую строку:

Переменная HISTCONTROL принимает список значений, разделенных двоеточиями, которые определяют способ сохранения команд в списке истории:

  • ignorespace — команды, начинающиеся с пробела, не сохраняются в списке истории.
  • ignoredups — повторяющиеся команды не сохраняются.
  • ignoreboth — это сокращение, включая как ignorespace и ignoredups .

Когда HISTTIMEFORMAT переменная HISTTIMEFORMAT , Bash HISTTIMEFORMAT времени выполнения команды в каждой строке.

Например, если вы установите:

История будет отображаться в следующем формате:

Выводы

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

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

The Power of Linux “History Command” in Bash Shell

We use history command frequently in our daily routine jobs to check history of command or to get info about command executed by user. In this post, we will see how we can use history command effectively to extract the command which was executed by users in Bash shell. This may be useful for audit purpose or to find out what command is executed at what date and time.

By default date and timestamp won’t be seen while executing history command. However, bash shell provides CLI tools for editing user’s command history. Let’s see some handy tips and tricks and power of history command.

history command examples

1. List Last/All Executed Commands in Linux

Executing simple history command from terminal will show you a complete list of last executed commands with line numbers.

2. List All Commands with Date and Timestamp

How to find date and timestamp against command? With ‘export’ command with variable will display history command with corresponding timestamp when the command was executed.

Meaning of HISTTIMEFORMAT variables

3. Filter Commands in History

As we can see same command is being repeated number of times in above output. How to filter simple or non destructive commands in history?. Use the following ‘export‘ command by specifying command in HISTIGNORE=’ls -l:pwd:date:’ will not saved by system and not be shown in history command.

4. Ignore Duplicate Commands in History

With the below command will help us to ignore duplicate commands entry made by user. Only single entry will be shown in history, if a user execute a same command multiple times in a Bash Prompt.

5. Unset export Command

Unset export command on the fly. Execute unset export command with variable one by one whatever commands have been exported by export command.

6. Save export Command Permanently

Make an entry as follows in .bash_profile to save export command permanently.

7. List Specific User’s Executed Commands

How to see command history executed by a specific user. Bash keeps records of history in a

/.bash_history’ file. We can view or open file to see the command history.

8. Disable Storing History of Commands

Some organization do not keep history of commands because of security policy of the organization. In this case, we can edit .bash_profile file (It’s hidden file) of user’s and make an entry as below.

Save file and load changes with below command.

Note: If you don’t want system to remember the commands that you have typed, simply execute below command which will disable or stop recording history on the fly.

Tips: Search ‘HISTSIZE‘ and edit in ‘/etc/profile’ file with superuser. The change in file will effect globally.

9. Delete or Clear History of Commands

With up and down arrow, we can see previously used command which may be helpful or may irate you. Deleting or clearing all the entries from bash history list with ‘-c‘ options.

10. Search Commands in History Using Grep Command

Search command through ‘.bash_history‘ by piping your history file into ‘grep‘ as below. For example, the below command will search and find ‘pwd‘ command from the history list.

11. Search Lastly Executed Command

Search previously executed command with ‘Ctrl+r’ command. Once you’ve found the command you’re looking for, press ‘Enter‘ to execute the same else press ‘esc‘ to cancel it.

12. Recall Last Executed Command

Recall a previously used specific command. Combination of Bang and 8 (!8) command will recall number 8 command which you have executed.

13. Recall Lastly Executed Specific Command

Recall previously used command (netstat -np | grep 22) with ‘!‘ and followed by some letters of that particular command.

We have tried to highlight power of history command. However, this is not end of it. Please share your experience of history command with us through our comment box below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Читайте также:  Windows help and support error
Оцените статью