Linux history all lines

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.

Читайте также:  Installing git bash windows

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 Linux Command Line History

You may want to clear the history file and the screen for security reasons. Some Linux distributions may clear the screen when you logout but others do not. Many programs read input as a single line at a time.

The GNU history library is able to keep track of those lines, associate arbitrary data with each line, and utilize information from previous lines in composing new ones. Bash and other shells may use this history library. The default file is

Bash’s history feature

bash’s history function depends on a variable called HISTFILE, normally set to the current user’s .bash_history file (located in the user’s home directory). When echoed, it returns the full path and name of the user’s history file, like so:

1) Remove Linux history command

History can be reset with some command but after the operation, if you logout and login in your shell, you will see the same history

a. Delete the previous commands

You can use history -c command to clear the previous history command 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.

The example below shows our current history

Now let’s use the command.

When you exit bash, the history is saved to the history file. The history created during the current session is appended to the file, entries that are already present are unaffected. Let’s check the new history

Let us add some command to our history.

To overwrite the history file with the current shell’s history, run history -w after history -c command

After login again, let’s us check our history

You can see that our history begin at history -w entry command.

b. Delete a single command

You can delete the history’s entries which you don’t want with the -d option. This will delete the history entry at position offset. But when you close terminal and open it again histories are not deleted. So we finally use history -w to save the changes.

Читайте также:  Windows 10 как откатиться назад

Now, if you want to delete the sixth entry which is mkdir command just use:

You can see that we didn’t have mkdir command entry above.

2) Clear bash completely

To clear the bash history completely on the server, an alternative solution is to link

/.bash_history to /dev/null

However, one annoying side-effect is that the history entries is linked to the memory and it will flush back to the file when you log out. To workaround this, you can use the following command:

3) Turn off bash history

You can stop logging history using one of the two ways: turn it off for all users, or turn off logging history for a single user.

a. Turn off for all users

You can turn off the bash history for all user adding unset HISTFILE line in /etc/profile file. This line deactivate the history file of each user on the system

You need to have the permission to apply the command above

b. Turn off for a specific user

The command above, it is possible to turn off the bash history of a specific user. You just need to indicate his bash_profile file.

Every the user will login, his history will be reset as below. All his history command will save until user logout

c. Edit .bashrc

You can remove the history command by editing two values of history command parameters.

  • HISTSIZE which is the number of lines or commands that are stored in memory in a history list while your bash session is ongoing
  • HISTFILESIZE which saves the amount of lines used for the history stack when it’s written to the history file.

To do it, edit your .bashrc and add

Now you can successfully delete the bash history and even stop logging to bash history using any of the above-listed commands.

4) Delete some entries lines

You can use history -d offset built in to delete a specific line from the current shell’s history. It’s not really practical if you want to remove a range of lines since it only takes one offset as an argument, but you could wrap it with a loop.

Just this one liner in the command prompt will help.

for i in <1..N>; do history -d START_NUM; done

Where START_NUM is starting position of entry in history N is no of entries you may want to delete.

Let’s check the last 15 entries of our history command

Now let us delete 13 entries beginning at the line 986

for i in <1..13>; do history -d 986; done

Now let’s check the result

You can see that we don’t have the same result.

When a user logs in with either a login or interactive/non-login shell, the user’s .bash_history file is opened. Now can operate on this file with some useful commands. The history is useful to retrieve commands used before but you can need to delete some entries of theses used commands. The

/.bash_history file does not record what you type in response to other programs’ prompts, just what you type at the bash prompt itself.

Источник

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

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

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

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

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

Читайте также:  Teamviewer ������� ��� mac os

Для дополнительных действий с историей вам могут понадобиться опции. Команда 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 и какие настройки можно использовать для более комфортной работы. Если у вас остались вопросы, спрашивайте в комментариях!

Источник

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