Linux History Command: How to Display the Date and Time of Command Execution

In Linux systems, the <span>history</span> command is a simple yet powerful tool that allows users to view and reuse previously executed commands. However, by default, the output of the <span>history</span> command only shows the command number and content, without including the date and time of command execution. This may not be intuitive enough for users who need to track the execution time of commands, and it can even become a significant obstacle in their work.

Linux History Command: How to Display the Date and Time of Command Execution

1. Introduction to the <span>history</span> Command

<span>history</span> is a built-in command in the Linux shell (usually Bash) that displays a list of commands executed by the user in the current session. Its default output format is as follows:

Linux History Command: How to Display the Date and Time of Command Execution

Each line includes a command number and the corresponding command content. This command history is maintained by the shell, stored in memory, and written to the default history file (for Bash, usually <span>~/.bash_history</span>) when the user exits the shell.

<span>history</span> serves the core purpose of helping users quickly review and repeat operations. For example, you can re-execute the third command (<span>vim file.txt</span>) by typing <span>!3</span>, or use <span>!!</span> to repeat the last command. However, by default, the <span>history</span> command does not provide time information, which limits its functionality.

2. Why Display Date and Time?

In practical use, understanding the date and time of command execution has several important reasons:

  • Troubleshooting: Timestamps can help users accurately determine whether a certain operation is related to system issues. For example, you may need to confirm whether a command was executed before a server crash.
  • Auditing and Monitoring: In multi-user environments, administrators may need to track user operations, and timestamps are essential clues.
  • Personal Records: For individual users, recording the execution time of commands can serve as a work log for future reference.

The default <span>history</span> output does not meet these needs, so we need to configure it to display the date and time.

3. How to Display Date and Time in the <span>history</span> Command

To display the date and time in the <span>history</span> command, the key is to set the <span>HISTTIMEFORMAT</span> environment variable. This variable controls the timestamp format when the <span>history</span> command outputs.

3.1 Setting <span>HISTTIMEFORMAT</span>

To temporarily set the <span>HISTTIMEFORMAT</span>, enter the following command in the terminal:

export HISTTIMEFORMAT="%F %T "
  • <span>%F</span>: Represents the full date (format: <span>YYYY-MM-DD</span>, e.g., <span>2023-10-01</span>).
  • <span>%T</span>: Represents the time (format: <span>HH:MM:SS</span>, e.g., <span>12:34:56</span>).
  • Space: Used to separate the date, time, and command content.

After setting, running the <span>history</span> command will change the output to:

Linux History Command: How to Display the Date and Time of Command Execution

Now, each command is preceded by a clear timestamp, showing when the command was recorded in history.

3.2 Meaning of the Timestamp

It is important to note that the timestamp displayed by the <span>history</span> command is not the actual start time of the command execution, but rather the time the command was recorded in history. In most cases, these two are nearly the same, but when multiple commands are executed in quick succession, the timestamp may have a slight delay. However, this minor difference usually does not affect daily use.

3.3 Permanent Setting of <span>HISTTIMEFORMAT</span>

The above setting is only valid for the current terminal session and will be lost when the terminal is closed. To apply this setting permanently, you can add the command to the user’s Bash configuration file (usually <span>~/.bashrc</span>):

  1. Open the <span>~/.bashrc</span> file:
vim ~/.bashrc
  1. Add the following line at the end of the file:
export HISTTIMEFORMAT="%F %T "
Linux History Command: How to Display the Date and Time of Command Execution
  1. Save and close the file, then run the following command to make the changes effective:
source ~/.bashrc
Linux History Command: How to Display the Date and Time of Command Execution

From now on, every time you log into the terminal, the <span>history</span> command will automatically display timestamps.

3.4 Custom Timestamp Format

<span>HISTTIMEFORMAT</span> supports various formatting options based on the syntax of the <span>strftime</span> function. Here are some common format examples:

  • <span>"%Y-%m-%d %H:%M:%S"</span>: Displays as <span>2023-10-01 12:34:56</span>.
  • <span>"%d/%m/%Y %T"</span>: Displays as <span>01/10/2023 12:34:56</span>.
  • <span>"%F %T %Z"</span>: Displays as <span>2023-10-01 12:34:56 CST</span> (including timezone).

You can choose a suitable format based on your needs. For example:

export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S %Z "

4. More Uses of the <span>history</span> Command

In addition to displaying timestamps, the <span>history</span> command also provides a wealth of options and features, detailed as follows.

4.1 Display a Specified Number of History Records

Using <span>history n</span> can display the last n commands. For example:

history 5
Linux History Command: How to Display the Date and Time of Command Execution

This will output the last 5 commands along with their timestamps (if <span>HISTTIMEFORMAT</span> is set).

4.2 Search History Records

By combining with the <span>grep</span> command, you can quickly search for specific history records. For example:

history | grep vim
Linux History Command: How to Display the Date and Time of Command Execution

This will list all commands containing “vim”, making it easy to find.

4.3 Clear Command History

Using <span>history -c</span> can clear the command history in memory for the current session:

history -c

Note that this will not affect the records in the <span>~/.bash_history</span> file.

4.4 Write to History File

By default, command history is written to the file at the end of the session. Using <span>history -w</span> can immediately write the history in memory to the file:

history -w

4.5 Execute Commands from History

  • <span>!n</span>: Execute the command with number n. For example:
!3

This will execute the third command.

  • <span>!!</span>: Repeat the last command.
  • <span>!string</span>: Execute the most recent command starting with “string”. For example:
!cd

This will execute the most recent <span>cd</span> command.

4.6 View Complete History

The <span>history</span> command without parameters will display all history records (limited by <span>HISTSIZE</span>, see below).

5. Customize Command History Behavior

Bash provides several environment variables to further customize the behavior of the <span>history</span> command.

5.1 <span>HISTFILE</span>: Specify History File Path

The default history file is <span>~/.bash_history</span>, but it can be changed using the <span>HISTFILE</span> variable:

export HISTFILE=~/my_history

From then on, command history will be saved in <span>~/my_history</span>.

5.2 <span>HISTFILESIZE</span>: Set History File Size

<span>HISTFILESIZE</span> controls the maximum number of command entries saved in the history file, with a default value usually set to 500 or 1000. Set it to a larger value:

export HISTFILESIZE=10000

5.3 <span>HISTSIZE</span>: Set Memory History Size

<span>HISTSIZE</span> controls the number of commands saved in memory, with a default value the same as <span>HISTFILESIZE</span>:

export HISTSIZE=10000

5.4 <span>HISTCONTROL</span>: Control Recording Rules

<span>HISTCONTROL</span> determines which commands are recorded. Common options include:

  • <span>ignorespace</span>: Ignore commands that start with a space.
  • <span>ignoredups</span>: Ignore duplicate commands.
  • <span>ignoreboth</span>: Apply both of the above.

Example:

export HISTCONTROL=ignoreboth

5.5 <span>HISTIGNORE</span>: Ignore Specific Commands

<span>HISTIGNORE</span> specifies command patterns that should not be recorded. For example:

export HISTIGNORE="ls:cd:pwd:exit"

This will ignore the <span>ls</span>, <span>cd</span>, <span>pwd</span>, and <span>exit</span> commands.

5.6 Real-time Saving of History

By default, history is written to the file at the end of the session. To save it in real-time, you can set the <span>PROMPT_COMMAND</span>:

export PROMPT_COMMAND="history -a"

This will append to the history file immediately after each command execution.

6. Command History Management in Multi-user Environments

In multi-user systems, each user has an independent command history file (located in their home directory at <span>~/.bash_history</span>). This ensures the isolation of history records.

6.1 View Other Users’ Command History

Administrators can use the following command to view a specific user’s command history:

sudo cat /home/username/.bash_history

6.2 Share Command History

If multiple sessions need to share history, the following settings can be used:

export PROMPT_COMMAND="history -a; history -c; history -r"
  • <span>history -a</span>: Append the current session history to the file.
  • <span>history -c</span>: Clear the current memory history.
  • <span>history -r</span>: Reload history from the file.

7. Using the <span>history</span> Command in Scripts

<span>history</span> command can also play a role in shell scripts.

7.1 Record Script History

Specify an independent history file in the script:

export HISTFILE=~/script_history

Commands in the script will be recorded in <span>~/script_history</span>.

7.2 Execute Specific History Commands

Find and execute specific commands:

last_cmd=$(history | grep "specific_command" | tail -1 | awk '{print $2}')

if [ -n "$last_cmd" ]; then

    eval "$last_cmd"

fi

8. Advanced Tips

8.1 Check Timestamps in History File

For old commands, the <span>~/.bash_history</span> may not contain timestamp information. After setting <span>HISTTIMEFORMAT</span>, only new commands will record timestamps.

8.2 Prevent History from Being Overwritten

In multi-session environments, use <span>shopt -s histappend</span> to ensure history is appended rather than overwritten:

shopt -s histappend

Linux History Command: How to Display the Date and Time of Command Execution

Important! Operations and Maintenance Discussion Group Open for External Access!Scan the code to add the editor’s WeChat,apply to join the groupLinux History Command: How to Display the Date and Time of Command Execution▲ Long press to join the group

Leave a Comment