Linux terminal output history

Getting the most out of Linux Bash history command

The Linux command line – the terminal – stores history of commands executed in the past by a user. This history is persistent and remains in memory even if we reboot our system. We can retrieve and reuse these stored commands to make the most of the history storage feature of the bash shell.

The Linux bash has a very powerful command called “history”. This command is a built-in bash command that is used to extract history information about commands that have been executed by Linux users in all previous sessions. In this tutorial, we will enable you to get the most out of your shell history by learning the proper use of the history command. Linux stores the command history for a particular user in a

/.bash_history file by default.

We will use the Linux terminal application to execute the commands mentioned in this tutorial.

Viewing the Entire Bash History

A user can view the entire history for his/her shell commands from the history file saved exclusively for that user by using the following simple command:

The history will be printed on the screen in the following default format:

In the above image, you can see a list of all commands with a number assigned to each of them. The number 1 command corresponds to the first command you ran and the last numbered command represents the latest command you executed.

If you have been running a lot of commands since using the bash, you will observe that there will be hundreds and even thousands of those commands displayed here. To access a few relevant commands, you can filter the results displayed by the history feature. You can also customize the history command to show a specific number of commands for you.

Filtering the Bash History Output

If you want to filter your history output based on a specific keyword that you might have used in the previous commands, you can use the history command as follows:

Example: In this example, I want to view only the ping commands I have ever run in the shell. Therefore, I will use the following command:

$ history | grep ping

You can see that my output now displays only the commands including my search keyword “ping” Advertisement

Viewing a Number of recently executed shell commands

You can also view a specific number of commands, for example:

  • N number of recent commands

OR

  • N number of oldest commands

N Number of Recent Bash Commands

You can view a specific number of recently run commands through the following command:

Example:

In this example, I want to view the last 3 commands that I ran, with the keyword ‘ping’ :

The output only displays the 3 recent ping commands instead of the entire history

N Number of Oldest Bash Commands

You can view a specific number of the oldest run commands through the following command:

Читайте также:  Как удалить историю с линукса

Example:

In this example, I want to view the oldest 3 commands that I ran, with the keyword ‘ping’ :

The output only displays the 3 oldest ping commands instead of the entire history

List All Bash Commands with Date and Timestamp

If you wish to view your command history along with the date and timestamp, please use the following export command:

Now when you wish to view the history, just run the history command to see the output in the following format:

Please note that this change in format is temporary and it will be restored to the previous standard when you close the session.

While you are on the command line, you can navigate through previously run commands and also recall some recently used commands by providing a keyword.

Scrolling through Commands

You can use the following keyboard controls to navigate through history commands

Up Arrow/Ctrl+P Using these controls, you can display the previous command you used. You can hit these controls multiple times to go back to a specific command in history.
Down Arrow/Ctrl+N Using these controls, you can display the next command you used. You can hit these controls multiple times to move forward to a specific command in history.
Alt+R If you edit a command, that you have pulled from the history, on a current line, you can use this control to revert it to the original command.

Recalling Commands

You can recall, run or choose not to run a specific command from the history, using the following controls:

Ctrl+R Using this control, you can recall a command from the history by specifying a search string.
Ctrl+O Using this control, you can run the command you recalled through Ctrl+R
Ctrl+G Using this control, you can exit history without running the command you recalled through Ctrl+R

Example:

In this example, I pressed ctrl+R and then provided the search string ‘ar’. The history displayed the command ‘arch’.

When I ran the command ‘arch’ by pressing ctrl+O, it displayed the CPU architecture of my system:

Utilizing the Bash History

The real magic of the bash history is by using various commands and customizing the history command itself to make the best use of the history feature:

Running Commands from History

  • As we have seen before, the history command displays the commands by associating a number with each. By using the following command, you can run a certain command from history, based on its number:

Example:

Here I am running the command number 95 from my history:

The output displays the result of ‘lscpu’ which was listed as command number 95 in my bash history. This command displays my CPU and operating system specifications.

  • You can re-run your previous command by using the following command:

Example:

Here you can see that I ran the command ‘arch’. By running the above-mentioned command, I can re-run the ‘arch’ command to view my CPU architecture as follows:

  • In order to search for a command from history and then run it, use the following command:

Example:

I will use the following command to re-run the last command with the keyword ‘dconf’ in it:

You can re-confirm in the following image that it was the last dconf command I had run.

Using Arguments from Previous Commands

Linux bash enables you to run a new command by using arguments from the previous command. It is especially helpful when you want to avoid retyping long or complicated arguments. You can use the following command for this purpose:

Using the last argument from the previous command

The variable !$ has the last argument from the previous command stored in it.

Example:

In this example, I will create a file with a long name.

I will then copy it to another location by avoiding to type the long name again as follows:

You can see that I was able to copy a file without retyping the filename by using the variable !$

Using the first argument from the previous command

Sometimes, only the first argument from the previous command is helpful in the current one.

In that case, you can use the following command:

Example:

In the following example, I ran the ping command by specifying the hostname and a count as arguments. Now I want to use the hostname(first argument) rather than 2(the last argument) in my new command. I will use the following command for this purpose:

Using all the arguments from the previous command

You can also use all the arguments from the previous command by using the following command:

Using one argument from a history command

You can also use commands from your history by re-using their arguments. Use the following command for this purpose:

Example:

This command will take the following parameters:

#:2(second argument of the command)

Following output shows the 2nd argument of the last cp command I ran:

Using all arguments from a history command

The following command will store all the arguments from the searched history command and use them in the current command:

Example:

In the following command, I will print all the arguments of the last cp command by using the echo command as follows:

Modifying and Running Previous Commands

If you mistyped a command or you want to re-run a command by changing some text in it; following is the way to do so:

Example:

I mistyped the command ‘grep’ as ‘gep’ and now I want to run the command by correcting the text:

Now you can see that my corrected command will run properly as follows:

Clearing History

In order to erase the history of your bash, use the following command:

This command clears your history and removes all contents from the

In this tutorial, we learned that while printing out the entire history contents is not that useful, optimizing the output with the commands we learned is the real game-changer. By practicing with this article, you will be able to display exactly the commands you want, re-execute and re-use those commands, and also use arguments from previously executed commands to optimize new commands.

Karim Buzdar

About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn

Источник

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

Источник

Читайте также:  Hp system management homepage linux
Оцените статью