- How to delete a single command from history on a Linux/Unix Bash shell
- How do I view history with line number?
- How to delete a single command number 1013 from history in Linux
- How do I delete all the history?
- Tip: Control bash history like a pro
- Where to find more information about history command?
- Conclusion
- Команда History в Linux (История Bash)
- Использование команды history и расширений истории
- Сохранение списка истории
- История очистки
- Изменение поведения в истории
- Выводы
- The Power of Linux “History Command” in Bash Shell
- 1. List Last/All Executed Commands in Linux
- 2. List All Commands with Date and Timestamp
- 3. Filter Commands in History
- 4. Ignore Duplicate Commands in History
- 5. Unset export Command
- 6. Save export Command Permanently
- 7. List Specific User’s Executed Commands
- 8. Disable Storing History of Commands
- 9. Delete or Clear History of Commands
- 10. Search Commands in History Using Grep Command
- 11. Search Lastly Executed Command
- 12. Recall Last Executed Command
- 13. Recall Lastly Executed Specific Command
- If You Appreciate What We Do Here On TecMint, You Should Consider:
How to delete a single command from history on a Linux/Unix Bash shell
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.
Источник