2 minute read

In the vast realm of Linux, mastering the command line is a valuable skill that empowers users to navigate, control, and customize their systems with precision. One often overlooked yet immensely useful feature at your disposal is the command history. Imagine having the ability to effortlessly recall and re-execute previously used commands, saving you time and effort. This is where the command history becomes your trusted companion.

In this article, we will delve into the fascinating world of Linux command history. We will explore how you can leverage this powerful tool to streamline your workflow, improve productivity, and gain a deeper understanding of your command line interactions. Whether you’re a Linux newcomer or an experienced user looking to enhance your efficiency, this guide will provide you with the knowledge and techniques to make the most of command history.

Running commands from history:

To display command history, type ‘history’ and press Enter. It will show numbered commands from the history. To run a specific command from history, type ‘!nr’, where ‘nr’ is the command number in history. For example, if you want to run command number 42, type ‘!42’ and press Enter. Environment variables and history formatting:

To add date and time to command history, you can set the environment variable ‘HISTTIMEFORMAT’. For example, in the terminal, type:

export HISTTIMEFORMAT="%F %T "

The above format ‘%F %T’ represents date and time in ISO 8601 format. After applying this change, new commands will include date and time information in the history. Formatting history:

Command history can be formatted using options of the ‘history’ command. Here are a few examples: ‘history -c’: Clear command history. ‘history -d nr’: Delete the command with the specified number ‘nr’ from history. ‘history -a’: Save the current state of history to the file ‘~/.bash_history’. You can find more options by typing ‘man history’ in the terminal. Synchronizing history between sessions:

Command history is typically saved in the ‘~/.bash_history’ file for most shells. To synchronize history between sessions, follow these steps: After executing important commands, type ‘history -a’ to save the current state of history to the ‘~/.bash_history’ file. To load history from the ‘~/.bash_history’ file in a new session, type ‘history -r’. Examples:

Displaying command history:

history

Running a command from history:

!42

Setting the HISTTIMEFORMAT environment variable:

export HISTTIMEFORMAT="%F %T "

Formatting history: Clearing command history:

history -c

Deleting command number 15 from history:

history -d 15

Saving the current state of history to the file ‘~/.bash_history’:

history -a

Please note that the examples assume the usage of the Bash shell.