How to linux command history

How can I see all of the bash history?

In this case, the shell can not see the history executed by shell(1), but I want to see all of the bash history in every shell. So my question is how can I see all of the bash history? Does anybody know how to hack? Thank you very much in advance!

5 Answers 5

would also work, although I tend to just use

How to do it when I am working in a virtual environment (venv)? ~/.bash_history shows only the commands outside of the virtual environment.

@Raif — you would need access to the terminal within the virtual environment as the «user» running the app commands (root or the equivalent).

You should look into the histappend shell option and the -a flag to history :

histappend

If set, the history list is appended to the file named by the value of the HISTFILE variable when the shell exits, rather than overwriting the file.

history

-a Append the «new» history lines (history lines entered since the beginning of the current bash session) to the history file.

If you put history -a into your PROMPT_COMMAND , you’ll get an always-up-to-date .bash_history file.

Edit your .bashrc and append this to it’s end:

shopt -s histappend PROMPT_COMMAND="history -n; history -a" unset HISTFILESIZE HISTSIZE=2000 

You can install something like Advanced Shell History, which will log each command to a sqlite3 database. It comes with a tool for querying the database from the command line. https://github.com/barabo/advanced-shell-history

With this setup, you will have a unified view of command history across all sessions. You also get things like command history for the current working directory (or subtree), command exit code, command duration, etc.

Full disclosure: I wrote and maintain the tool.

As several have noted, you need to use shopt -s histappend . Check by running shopt and verifying that histappend is ‘on’.

To ensure that each command (across multiple concurrent shells) appears in the history for each of those shells, add this at the end of your .bashrc file:

# Skip if not an interactive shell if [ -z "$" ]; then return; fi export PROMPT_COMMAND="history -a; history -c; history -r; $" 

-a: appends the new history lines (history lines entered since the beginning of the current Bash session) to the history file.

-c: clears the history list.

-r: reads the current history file and append its contents to the history list.

Run source .bashrc or create new sessions and in several terminal windows enter the comment #Tn in each. Then on one terminal, enter history | tail -N to see the last N lines. You should see all of the comments entered on the different terminals.

It may be helpful to add the following to /etc/profile.d/bashrc.sh in order to get a timestamp on each line of the history:

if [ -z "$" ]; then return; fi export HISTTIMEFORMAT='%F %T ' 

The result looks like this:

 [moi@laBoheme ~]$ history | tail -4 3292 2019-01-22 12:41:25 # T1 3293 2019-01-22 12:41:32 # T2 3294 2019-01-22 12:41:44 # T3 3295 2019-01-22 12:41:50 history | tail -4 

Источник

Читайте также:  Linux on my samsung debian

How to Use the Linux history Command

The history command in Linux is a built-in shell tool that displays a list of commands used in the terminal session. history allows users to reuse any listed command without retyping it.

In this tutorial, we will show you how the history command works and different ways to use it.

How to use the Linux history command

How to Use Linux history Command

Using the history command without options displays the list of commands used since the start of the terminal session:

Using the history command to display the command history list

To display the command history list with a limited number of entries, append that number to the history command. For instance, to show only the latest five entries, use:

Using the history command to display a limited number of command history list entries

Once you close the terminal, the Bash shell saves new command history entries in the .bash_history file.

Use Date and Timestamps

The .bashrc file stores the Bash shell settings. Modifying this file allows you to change the output format of the history command.

Open the .bashrc file using a text editor such as Nano:

To change the output format to include date and timestamps, add the following line to the .bashrc file:

Edit the .bashrc file to include timestamps in the history command output

Note: The blank space before the closed quotation marks prevents the timestamp from connecting to the command name, making the history list easier to read.

Using different arguments after HISTTIMEFORMAT allows you to customize the level of detail in the timestamp:

Save the changes to the .bashrc file, relaunch the terminal, and run the history command to confirm the new output format:

The history command output with timestamps

View the Size of the History Buffer

The .bashrc file contains two entries that control the size of the history buffer:

  • HISTSIZE : The maximum number of entries for the history list.
  • HISTFILESIZE : The maximum number of entries in the .bash_history file.

Entries defining the history buffer size

Editing the HISTSIZE and HISTFILESIZE values changes how the Bash shell displays and saves the command history.

For instance, changing the HISTSIZE value to 10 makes the history command list show a maximum of 10 latest entries.

Editing the history buffer size

Saving the changes to the .bashrc file, relaunching the terminal, and running the history command confirms the new output format:

The history command list with 10 entries

Repeat a Command

Running the history command allows you to reuse any of the commands on the list. For instance, to run the first command ( sudo apt update ) again, use:

Reusing the first command on the history list

Adding a dash () before the command number starts the count from the end of the list. For instance, to reuse the tenth last command ( history 5 ), use:

Reusing a command from the history list, counting from the end

Use double exclamation points to repeat the last command:

Reusing the last command

Search a Command by String

Adding a string after the exclamation point runs the latest command that starts with that string. For example, to reuse the latest command that begins with sudo , use:

Reusing a command starting with the

Using this method can cause problems if the shell runs an unexpected command, especially when searching for a command that starts with sudo . As a precaution, adding the :p argument displays the command without running it, allowing you to review the command and decide if you want to execute it.

Читайте также:  Linux scrolling in screen

Displaying the last command starting with the

To search for a command that contains a string, but may not start with it, add a question mark next to the exclamation point. For instance, to reuse the last command that contains echo :

Reusing the last command that contains the

In the example above, the shell reuses the last command that contains the echo string even though the command starts with sudo .

Check out our article on sudo command to learn how to use the sudo command with examples.

List the Matching Commands

Combining history and grep allows you to display a list of commands that contain a string. For example, to list all commands that contain ufw , use:

Searching the command history using the history and grep commands

Note: Learn more about using the grep command in Linux.

Change the Executed Command

Use the following syntax to change the last executed command:

For instance, the ufw command to enable port 20 shows that the port is already enabled:

Unsuccessfully running the ufw command

Use the syntax above to change the port number from 20 to 22:

Changing the previous command

Prevent Recording Commands in History

To prevent recording commands in the history list, temporarily disable recording by using:

To re-enable recording, use:

Delete History

Use the -d option with the history command to delete a command from the history list. For instance, delete command number 87 with:

Deleting an entry from the command history list

Use the -c option to clear the whole history list:

Update the History File

The Bash shell saves any updates to the command history list when you exit the terminal session. The history command also allows you to save changes while in the terminal session.

Using the -a option lets you append the command history entries from this session to the .bash_history file:

Another method is to use the -w option to save the entire history list to the .bash_history file:

After reading this tutorial, you should be able to use the history command in Linux to view, edit, and delete the command history list and reuse commands from it.

If you are interested in learning more about Linux commands, have a look at our Linux commands cheat sheet.

Источник

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

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

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

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

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

Для дополнительных действий с историей вам могут понадобиться опции. Команда history linux имеет очень простой синтаксис:

$ history опции файл

В качестве файла можно указать файл истории. По умолчанию история для текущего пользователя хранится в файле ~/.history, но вы можете задать, например, файл другого пользователя. А теперь рассмотрим опции:

  • -c — очистить историю;
  • -d — удалить определенную строку из истории;
  • -a — добавить новую команду в историю;
  • -n — скопировать команды из файла истории в текущий список;
  • -w — перезаписать содержимое одного файла истории в другой, заменяя повторяющиеся вхождения.
Читайте также:  Разархивировать архив linux tar gz

Наиболее полезной для нас из всего этого будет опция -c, которая позволяет очистить историю команд linux:

Так вы можете посмотреть только последние 10 команд:

А с помощью опции -d удалить ненужное, например, удалить команду под номером 1007:

Если вы хотите выполнить поиск по истории bash, можно использовать фильтр grep. Например, найдем все команды zypper:

На самом деле работать с историей еще более просто с помощью оболочки, возможно, вы уже используете многие ее функции, но о некоторых точно не знаете. Рассмотрим их:

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

Вы можете выполнить последнюю команду просто набрав «!!». Также можно выполнить одну из предыдущих команд указав ее номер «!-2»

Чтобы выполнить поиск по истории прямо во время ввода нажмите Ctrl+R и начните вводить начало команды.

Если вы знаете, что нужная команда была последней, которая начиналась на определенные символы, например, l, то вы можете ее выполнить, дописав «!l»:

Если нужная команда последняя содержала определенное слово, например, tmp, то вы можете ее найти, использовав «!?tmp»:

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

Таким образом, вы можете очень быстро отыскать нужную команду, если помните как она была написана. История команд bash хранит очень много команд и этого вполне достаточно для комфортной работы.

Настройка истории Linux

Linux — очень настраиваемая и гибкая система, поэтому настроить здесь можно все, в том числе и историю. По умолчанию выводится только номер команды, но вы можете выводить и ее дату. Для этого нужно экспортировать переменную HISTORYFORMAT вместе нужным форматом:

export HISTTIMEFORMAT=’%F %T ‘
$ history

Для форматирования можно использовать такие модификаторы:

Вы можете указать какие команды не стоит отображать, например, не будем выводить ls -l, pwd и date:

export HISTIGNORE=’ls -l:pwd:date:’

Также можно отключить вывод одинаковых команд:

Существует два флага, ignoredups и ignorespace. Второй указывает, что нужно игнорировать команды, начинающиеся с пробела. Если вы хотите установить оба значения, используйте флаг ignoreboth. Используйте переменную HISTSIZE, чтобы установить размер истории:

По умолчанию история сохраняется для каждого терминала отдельно. Но если вы хотите чтобы все ваши команды немедленно синхронизировались между всеми терминалами, то это очень просто настроить. Добавьте такую переменную:

export PROMPT_COMMAND=»$history -a; history -c; history -r;»

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

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

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

Выводы

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

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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