- Set Date and Time for Each Command You Execute in Bash History
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Linux – дата и время в history
- Увеличиваем Размер Хранимой Истории
- Добавляем Команды Bash в Файл с Историей
- Добавляем Команды Bash в Файл с Историей
- Мгновенно Сохранять Историю Команд
- Игнорировать Определенные Команды
- Одна Команда — Одна Запись в Истории
- Применить настройки:
- Bash History Display Date And Time For Each Command
- Bash History Display Date And Time For Each Command
- How to see time stamps in bash history
- How to retrieve Linux or Unix bash command line history by date and time
- Controlling Bash history behavior
- Other shell variables
- Conclusion
- Bash History: How To Show A Timestamp (Date / Time) When Each Command Was Executed
Set Date and Time for Each Command You Execute in Bash History
By default, all commands executed by Bash on the command line are stored in history buffer or recorded in a file called
/.bash_history. This means that a system administrator can view a list of commands executed by users on the system or a user can view his/her command history using the history command like so.
Linux History Command
From the output of the history command above, the date and time when a command was executed is not shown. This is the default setting on most if not all Linux distributions.
In this article, we will explain how you can configure time stamp information when each command in the Bash history was executed to be displayed.
The date and time associated with each history entry can be written to the history file, marked with the history comment character by setting the HISTTIMEFORMAT variable.
There are two possible ways of doing this: one does it temporarily while the other makes it permanent.
To set HISTTIMEFORMAT variable temporarily, export it as below on the command line:
In the export command above, the time stamp format:
- %F – expands to full date same, as %Y-%m-%d (year-month-date).
- %T – expands to time; same as %H:%M:%S (hour:minute:seconds).
Read through the date command man page for additional usage information:
Then check your command history as follows:
Display Linux Command History with Date and Time
However, if you want to configure this variable permanently, open the file
/.bashrc with your favorite editor:
And add the line below in it (you mark it with a comment as your own configuration):
Save the file and exit, afterwards, run the command below to effect the changes made to the file:
That’s all! Do share with us any interesting history command tips and tricks or your thoughts about this guide via the comment section 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.
Источник
Linux – дата и время в history
Давно хотел запостить статейку, как напоминалку для себя. Но не так давно, наш хороший товарищ Евгений опубликовал у себя на форуме опередив нас.
Итак, очень часто приходиться обращаться к bash history для информации, что и что делал на серваке, но вот тут засада, он не отображает ни даты, ни времени и мы попробуем с Вами узнать как отобразить время в Linux history время:
Для начала, что такое history – это команда, которая отображает список, а точнее историю вводимых команд, т.е. для просмотра последних вводимых команд достаточно ввести в терминале команду history и просмотреть всю историю, которая будет выглядеть например так:
Для того, что бы отображалось время, нужно определить формат переменной окружения HISTTIMEFORMAT, например указав дату и время в такой последовательности:
Где %d – день, %m – месяц, %y – год, %T – время, эту переменную необходимо добавить в свой .bash_profile:
Срузу уточню, тут кому как угодно или одной строкой в терминале как в примере ниже или открываете nano .bash_profile
Так же рекомендую перед сохранением настроек сделать следующие настройки:
Увеличиваем Размер Хранимой Истории
Увеличьте HISTSIZE — количество команд, которые необходимо запоминать в списке истории (стандартное значение — 500).
Увеличьте HISTFILESIZE — максимальное количество строк, содержащееся в файле истории (стандартное значение — 500).
Добавляем Команды Bash в Файл с Историей
Bash перезаписывает файл .bash_history?
Чтобы добавлять новые команды в файл с историей, а не переписывать его каждый раз, добавьте следующую строку в
Добавляем Команды Bash в Файл с Историей
Bash перезаписывает файл .bash_history?
Чтобы добавлять новые команды в файл с историей, а не переписывать его каждый раз, добавьте следующую строку в
Мгновенно Сохранять Историю Команд
По умолчанию, Bash записывает историю команд в .bash_history, при завершении сессии.
Если сессия внезапно оборвется Вы потеряете текущую историю команд.
Используйте переменную $PROMPT_COMMAND, чтобы сохранять команды сразу после выполнения:
Добавьте следующую строку в файл
/.bashrc, если переменная $PROMPT_COMMAND не была задана ранее:
Добавьте следующую строку, если переменная $PROMPT_COMMAND уже была задана:
Игнорировать Определенные Команды
HISTIGNORE — список шаблонов через двоеточие, используемых для принятия решения о сохранении строк с командами в списке истории.
Не сохранять команды ls, ps и history:
Не сохранять команды начинающиеся с s:
Одна Команда — Одна Запись в Истории
Сохранять все строки многострочной команды в одной записи списка истории:
Применить настройки:
Вводим пару команд, снова смотрим используя команду history:
Источник
Bash History Display Date And Time For Each Command
H ow do I display shell command history with date and time under a Linux, MacOS or Unix-like operating systems? How do I see date and time stamps in bash history command running on a Linux or Unix-like systems?
The bash shell provides access to the command history, the list of commands previously typed. The value of the HISTSIZE variable is used as the number of commands to save in a history list. If the HISTTIMEFORMAT is set, the time stamp information associated with each history entry is written to the history file, marked with the history comment character. This page shows how to display bash History with date and time when running the history command on a Linux or Unix-like systems.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Bash on Linux, macOS & Unix |
Est. reading time | 2 minutes |
Bash History Display Date And Time For Each Command
By default history command will display output as follows:
$ history
Sample outputs:
The above command won’t display what time the commands were executed from the bash history. To solve this problem create a shell variable called HISTTIMEFORMAT.
How to see time stamps in bash history
- %d – Day
- %m – Month
- %y – Year
- %T – Time
Use the source command to load HISTTIMEFORMAT from file into the current shell script or a command prompt:
$ .
/.bash_profile
OR
$ source
How to retrieve Linux or Unix bash command line history by date and time
Now, to see history, type:
$ history
Sample outputs:
Here is another output from my Ubuntu Linux server:
Fig.01: Adding date and time to my bash history
Controlling Bash history behavior
We can use the shopt command to control optional shell behavior for the history command under Linux, macOS and Unix-like OS. The syntax is:
Option | Description | Set value | Unset value |
---|---|---|---|
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. | set -s histappend | set -u histappend |
histreedit | If set, and readline is being used, a user is given the opportunity to re-edit a failed history substitution. | set -s histreedit | set -u histreedit |
histverify | If set, and readline is being used, the results of history substitution are not immediately passed to the shell parser. Instead, the resulting line is loaded into the readline editing buffer, allowing further modification. | set -s histverify | set -u histverify |
Other shell variables
We can set the following additonal variables for history command:
- 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 ➔
Environment variable (use the export command) | Description |
---|---|
HISTCONTROL=ignoreboth:erasedups | If the list of values includes ignorespace , lines which begin with a space character are not saved in the history list. Also ignoredups option causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups . We can set erasedups option that 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. |
PROMPT_COMMAND=»history -a; history -n» | Run history command before next prompt displayed. The -a option append history lines from this session to the history file. The -n read all history lines not already read from the history file and append them to the history list |
HISTIGNORE=»ls:ll:cd:pwd:bg:fg:history» | A colon-separated list of patterns used to decide which command lines should be saved on the history list. |
HISTSIZE=100000 | The number of commands to remember in the command history. |
HISTFILESIZE=10000000 | The maximum number of lines contained in the history file. |
Conclusion
You just learned how to display or see time stamps in bash history including date when the command were executed. For more info type the following commands or see gnu/bash page here:
man bash
help history
man 3 strftime
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
Источник
Bash History: How To Show A Timestamp (Date / Time) When Each Command Was Executed
Want to add a timestamp (date and time) next to each command from your Bash history? This can be done by using the HISTTIMEFORMAT Bash variable.
Bash keeps a history of the commands you type, which can be accessed by typing history . By default you see a number followed by the commands you’ve used recently:
With the help of the HISTTIMEFORMAT Bash variable you can show the date and time when each command was executed. This can be useful in various occasions, including to remember which commands you ran in a specific time-frame, to undo various operations, and so on.
It’s worth noting that if this variable is set, the time stamps are written to the history file, so they are preserved across shell sessions. So the first time you enable it, you won’t see the correct date and time for your previously used commands.
Another Bash history enhancement you might like: HSTR Makes Searching Your Bash Or Zsh Command History Easy
Set the Bash history to show a timestamp for your command history (for the current terminal session only) by using this command:
This command is only for this session, so you can see how it looks and optionally configure the date and time format (see below).
Now type history and you should see timestamp for your Bash history commands:
We’ve exported HISTTIMEFORMAT with the following timestamp:
- %F : full date (year-month-date)
- %T : time (hour:minutes:seconds)
There is a space after %T and before » , so that there’s a space in your Bash history between the time the command was executed and the command itself. Without it, the two wouldn’t be separated.
You can customize the date and time. Use HISTTIMEFORMAT=»%Y/%m/%d %T » to show the date as year(4 digits)-month-day, and time as hour(00..24):minutes:seconds. Show the date as month/day/year(2 digits) with %m/%d/%y . Want to show the time as 00..12 followed by AM / PM, instead of 00..24? Use %I:%M:%S %p as the time format. See the date command for how to further format the date and time.
It’s now time to export HISTTIMEFORMAT from your
/.bashrc file to make it default for all new terminal sessions for your user. You can either open your
/.bashrc file with a text editor and paste export HISTTIMEFORMAT=»%F %T » (or some other date and time format) at the bottom, then save the file, or you can run this command to write it to your
Run this command only once, because it adds export HISTTIMEFORMAT=»%F %T » to
/.bashrc each time you run it.
After this, all that’s left is to source the
/.bashrc file so the current terminal session uses the new settings (or you can open a new terminal and it will automatically pick up the new HISTTIMEFORMAT settings):
Remember: the first time you enable timestamps for your Bash history, you won’t see any date / time for your previously used commands. Only commands executed after you enable timestamps for your Bash history will show a date and time at the beginning of the line.
Источник