There are times when you need to recall all the flags and parameters of a command you used a couple of days ago.
In such cases, the Linux history command acts as a handy time machine for your Bash commands by remembering all the commands you have used. So, if you ever need to redo a command, correct a mistake, or compare what you’re doing now with what you did before, Linux Bash history has got your back. It’s an essential tool for system administrators and developers who need to boost efficiency and minimize errors.
The Linux history command is more than a simple recall tool. Users can find and edit old commands and control how the Bash terminal manages command history.
In this detailed tutorial, we will take a detailed look at the Linux history command and how you can use it to speed up and optimize your shell experience.
Table Of Contents
- How to Use The Linux History Command
- Correct Mistakes in the Executed Command
- Use Line Numbers to Repeat a Command
- Prevent Recording of Commands in Bash History
- Delete Command History in Bash
Let’s start with the prerequisites for using the command.
Before working with the Linux history command, make sure you have the following:
- A system running a Linux distribution.
- A user account with sudo privileges.
- Access to a terminal running Bash.
How to Use The Linux History Command
The following basic syntax of the Linux history command displays the entire command history for the current user:
If you are a power user or a sysadmin, you can imagine the long list of commands in the terminal. A more practical use of the history command is to limit the number of commands to a more manageable number. For this, simply add the number of commands you wish to see after the command in the following format:
For instance, use the following command to display the last five commands:
This command is especially useful when you know you’ve run a particular command recently but can’t remember the exact syntax or details.
The Linux history command is incredibly flexible, and you can fine-tune your experience to extract the desired information from the Bash history.
Search for Commands Containing a String
If you remember just a fragment of a command, you can quickly locate it by using the grep utility to search for the fragment. This saves you from scrolling through the long list of commands to locate the command.
You can easily pipe the output of the history command into the grep utility to search for the fragment. The syntax of this command is:
history | grep ‘’
For instance, the following command searches for all commands containing the term apt-get.
history | grep 'apt-get'
Another quick way to search through your command history is by using the reverse search functionality in Bash.
For this, press Ctrl + R in the terminal. Start typing the command or keyword you’re looking for. As you type, Bash will show the most recent command that matches your input.
If you want to see older matches, keep pressing Ctrl + R.
Once you’ve found the command, press Enter to execute it or Ctrl + J to place it at the cursor without executing it.
This interactive search method is especially useful for quickly finding and executing past commands. Both methods are invaluable for discovering and reusing commands from your Bash history, making your work in the terminal more efficient.
Set Date and Timestamps for the Bash Terminal
The .bashrc file contains the Bash shell settings. You can modify the terminal’s behavior by modifying the entries in this file.
Adding time and date information is another way of simplifying the search for our desired commands. You can adjust the level of detail in the timestamps by adding one or more of the following arguments with the HISTTIMEFORMAT variable.
- %d: Day
- %m: Month
- %y: Year
- %H: Hour
- %M: Minutes
- %S: Seconds
- %F: Full date (Y-M-D format)
- %T: Time (H:M:S format)
- %c: Complete date and timestamp (Day-D-M-Y H:M:S format)
You can easily add date and time information to the terminal commands by following these steps:
Open .bashrc with a Text Editor
Open the file in your preferred file editor. For this demonstration, we’ll use nano. So, we’ll open .bashrc in nano with the following command:
sudo nano .bashrc
Configure the Timestamp Information for Commands
Add the following line to the file to add date and timestamps to your command history;
export HISTTIMEFORMAT="%c "
The space before the closing quotation marks is essential for keeping the timestamp separate from the command name. You will see a significant improvement in the readability of your Linux history command list in the terminal.
Save and Apply Changes
Save the file and exit the editor. Next, relaunch the terminal to make sure the edited .bashrc file is in effect. Now, when you run the history command, you’ll see the commands with timestamps.
Set the Size of the History Buffer
In Bash, the size of the history buffer (the number of commands that Bash remembers) is determined by the HISTSIZE environment variable.
Before changing the value of this variable, listing the current value is a good idea. For this, simply echo the value of the variable in the terminal to see the maximum number of commands that are stored in the in-memory command history list:
Next, echo HISTFILESIZE, the variable that stores the number of commands stored in the history file (~/.bash_history):
If either of these variables is unset or set to null, there is no upper limit, allowing unlimited history size and unlimited history file size. However, in practice, many systems set default values to prevent the history from growing indefinitely.
The best practice here is to set the value in the ~/.bashrc or ~/.bash_profile files to ensure persistent behavior across sessions. For instance, typical values for these variables are:
These statements allow for 5000 commands in the in-memory history list and 10000 in the history file.
Correct Mistakes in the Executed Command
If you make a mistake in a command and execute it, you will not see the intended output.
Rather than retyping the long command, you can opt to quickly substitute the incorrect string with the correct one. The process will replace the first occurrence of the incorrect string with the correct one and then execute the command.
Here’s a demonstration of this idea.
Suppose that you executed the following command and then realized you had made a mistake.
echo helo world
You can do a quick substitution in the following format:
Bash will make the substitution and then immediately execute the corrected command:
echo hello world
Note that the substitution modifies and executes the last command only.
Use Line Numbers to Repeat a Command
The Linux history command assigns a number to each command. This is a very useful functionality because you can re-execute any command by prefixing its line number with !.
For instance, if the sudo apt update command is the first in the history list, run it again with the following command:
Note that this will immediately execute the command. Similarly, if you want to run any other command from the history list, just note its number and use the ! prefix followed by the command number.
If you don’t want to execute the command immediately, use the :p modifier:
This will print the command at the line number 1 in the command history without executing it.
Prevent Recording of Commands in Bash History
If you wish to temporarily disable recording commands in the history list for a Bash session, use the following command
set +o history
After issuing this command, any subsequent commands you run in the terminal session will not be saved to the history list.
If you want to re-enable history recording within the same session, use:
set -o history
Remember, this method only affects the current terminal session. If you open a new terminal or start a new session, history recording will be enabled by default.
Delete Command History in Bash
Bash offers several ways of deleting commands from the Bash history. Let’s cover three simple ways that involve terminal commands and file manipulation.
Clear the Current Session’s History
Use the history command with the -c option to clear the history for the current session:
Delete the History File
Bash typically saves the command history in the .bash_history file, located in the user’s home directory. You can remove the Bash command history by deleting this file with the rm command:
Stop Saving the History File
If you want to stop saving the command history to a file when you exit the terminal, unset the HISTFILE environment variable. Note that this is a temporary measure and only lasts for the current session:
If you wish to make this change permanent, add this line to the ~/.bashrc or ~/.bash_profile file.
Remember that these methods won’t protect you against other methods of monitoring or logging activities on the system. We recommend extreme caution when working on shared or monitored systems.
Update the History File
The history of commands executed in a Bash session is stored in memory and is typically written to the ~/.bash_history for the duration of the session. If you want to immediately write the in-memory command history to the history file without closing the session, use the history command with the -a option:
This is useful if you have multiple terminal sessions open and you want to save the command history from one session before starting another.
Use history -w to overwrite the contents of the ~/.bash_history file with the current session’s command history.
Use history -r to read and load the ~/.bash_history file’s content into the current session’s memory. This is a useful option if you need to use the contents of the file in the current session.
Finally, use history -n to read only the new entries from the ~/.bash_history file and append them to the current session’s memory. These are the commands executed in other terminal sessions since the start of the current terminal.
The Linux history command is a valuable tool for sysadmins and power users who spend a lot of time in the terminal. By quickly processing the command list and manipulating the command history, users can speed up and optimize their terminal experience. This is very beneficial when you are working in Linux environments.
If you’re looking for a robust server for your Linux projects, RedSwitches offers the best dedicated server pricing and delivers instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.
Q. What is the purpose of the Bash history command?
The Bash history command is a feature in Linux that allows users to view and manipulate their command history. It keeps track of the commands that have been entered by the user, allowing for quick access and reuse of previously executed commands.
Q. How can I view my command history in Linux?
To view your command history in Linux, use the history command. Simply type history at the command prompt, and a list of your previous commands will be displayed.
Q. How can I execute a previously executed command?
To execute a previously executed command, use the ! modifier. For example, if you want to execute the command that is listed as number 1 in your history, type ! followed by the command number.
Q. How can I modify the behavior of the Bash history command?
To modify the behavior of the Bash history command, use the export command. By setting specific environment variables, you can change settings such as the number of commands that are stored in the history, the format in which they are displayed, and more.
Q. How can I use the Bash history expansion feature?
Bash history expansion is a feature that allows you to use previous commands as part of a new command. Incorporate a specific command from your history into a new command by using an exclamation mark followed by a string, which allows you to reference and utilize it in the active voice. For example, if you want to run a command you previously used, type ! followed by a unique string.
Q. How can I check my current Bash history settings?
To check your current Bash history settings, use the set command. This will display all of the current settings for your Bash shell, including the history-related settings.
Q. How can I run a command multiple times from my Bash history?
To run a command multiple times from your Bash history, use the exclamation mark followed by the command number, followed by a colon, and the number of times you want to execute it. For example, if you want to execute the command number 1 five times, type !1:5.
Q. How can I learn Linux from the command line?
To learn Linux from the command line, start by understanding the basic commands and their usage. There are various online tutorials and resources available that can guide you through the process of learning Linux. Additionally, practice and hands-on experience with a Linux distribution, such as Red Hat Enterprise Linux, can help you become familiar with the command line.
Q. What is an advanced history command in Linux?
An advanced history command in Linux refers to using additional options and parameters with the basic history command to perform specific tasks. These advanced options can include filtering the history based on specific criteria, displaying the history in a specific format, or modifying the history list itself. Advanced history commands can help you navigate and manipulate your command history more efficiently.
Q. How can I prevent certain commands from being recorded in the Bash history?
To prevent certain commands from being recorded in the Bash history, modify the default Bash history settings. By setting the HISTIGNORE environment variable, specify a list of commands that should be ignored and not added to the history. This is useful for excluding sensitive commands or commands you don’t want to clutter your history.