Linux history all shells

How To Search Shell Command History

Q. How do I search old command history under bash shell? How do I display or modify previous commands?

A. Almost all modern shell allows you to search command history if enabled by user. Use history command to display the history list with line numbers. Lines listed with with a * have been modified by user.

Shell history search command

Type history at a shell prompt:
$ history
Output:
Sample output:

To search particular command, enter:
$ history | grep command-name
$ history | egrep -i ‘scp|ssh|ftp’

Emacs Line-Edit Mode Command History Searching

To get previous command containing string, hit [CTRL]+[r] followed by search string:

To get previous command, hit [CTRL]+[p]. You can also use up arrow key.

To get next command, hit [CTRL]+[n]. You can also use down arrow key.

fc command

fc stands for either “find command” or “fix command. For example list last 10 command, enter:
$ fc -l 10
To list commands 130 through 150, enter:
$ fc -l 130 150
To list all commands since the last command beginning with ssh, enter:
$ fc -l ssh
You can edit commands 1 through 5 using vi text editor, enter:
$ fc -e vi 1 5

  • 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

Delete command history

The -c option causes the history list to be cleared by deleting all of the entries:
$ history -c

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

Источник

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.

Читайте также:  Kaspersky endpoint security для windows 2003
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.

Источник

How To Clear Shell History In Ubuntu Linux

H ow do I clear the shell history in Ubuntu Linux? How can I clear terminal command history in Ubuntu Linux? How do I clear bash history completely on Ubuntu Linux?

Command history allows you to find and reissue previously typed commands. History expansions introduce words from the history list into the input stream, making it easy to repeat commands, insert the arguments to a previous command into the currentinput line, or fix errors in previous commands quickly. You may pass sensitive information such as passwords and it is stored in shell history file. Use the following tips to either delete your history or disable it.

Читайте также:  Как хранить пароли mac os
Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 1m

How to clear bash shell history command

The procedure to delete terminal command history are as follows on Ubuntu:

  1. Open the terminal application
  2. Type the following command to to clear bash history completely:
    history -c
  3. Another option to remove terminal history in Ubuntu:
    unset HISTFILE
  4. Log out and login again to test changes

Let us see all examples and usage in details to remove shell history in Ubuntu when using bash.

Finding info about your history

To get name of the history file, type:
echo «$HISTFILE»
/home/vivek/.bash_history
So my history is stored in /home/vivek/.bash_history file. It can store up to 1000 commands by default. To see your current settings run the following echo command echo «$HISTSIZE»
1000
To see current history, run:
history
history | grep ‘du’
The grep command used in last to filter out history.

Command to clear Ubuntu bash history

To clear the history, type the following command:
history -c
OR
rm

/.bash_history
You can add the command to your

/.bash_logout so that history will get cleared when you logout:
echo ‘history -c’ >>

  • 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

Prevent a bash history file from ever being saved

Add the following commands to

/.bashrc file:
echo ‘unset HISTFILE’ >>

/.bashrc
echo ‘export LESSHISTFILE=»-«‘ >>

A list of history shell variables

Bash shell variable Description/Usage
HISTFILE
echo $HISTFILE
export HISTFILE=

/.my_shell_history The name of the file in which command history is saved. The default is $HOME/.bash_history. HISTFILESIZE
export HISTFILESIZE=50000 The maximum number of lines contained in the history file. HISTSIZE
export HISTSIZE=50000 The number of commands to remember in the command history. The default is 500. If the value is 0, commands are not saved in the history list. HISTTIMEFORMAT
export HISTTIMEFORMAT=»%d/%m/%y %T « If this variable is set and not null, its value is used as a format string for strftime(3) to print the time stamp associated with each history entry displayed by the history builtin. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines. HISTIGNORE
# Ignore these commands
HISTIGNORE=»ls:pwd» A colon-separated list of patterns used to decide which command lines should be saved on the history list. HISTCONTROL
#Dont put duplicate lines in the history
export HISTCONTROL=ignoreboth A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored.

For more info read bash command man page online or offline by typing the following command:
man bash
help history
See “A Shell Primer: Master Your Linux, OS X, Unix Shell Environment” for more info.

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

Источник

История команд 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=»$history -a; history -c; history -r;»

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

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

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

Выводы

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

Источник

Читайте также:  Установка загрузчика linux рядом с windows
Оцените статью