The bash history command is a built-in shell feature that allows you to recall and reuse previous commands. It works by keeping a record of all the commands you enter in the shell and providing you with a way to recall them. You can access the history of your commands using the
How to use the bash history command
The most basic use of the bash history command is to recall a command that you previously entered. To do this, simply type
history at the command line, and you will see a list of your previously entered commands. You can then copy and paste the desired command from the list to reuse it.
Searching the history
You can search for specific commands in your history by using the
history command with the
grep command. For example, the following command will search your history for any commands that contain the word “ls”:
history | grep "ls"
Re-executing a command
You can re-execute a command from your history by typing an exclamation point (
!) followed by the command number. For example, to re-execute the third command in your history, you would type:
Re-executing a command starting with a string
You can re-execute the most recent command that starts with a given string by typing an exclamation point (
!) followed by the string. For example, to re-execute the most recent command that starts with “ls”, you would type:
Modifying a command before re-executing
You can modify a command from your history before re-executing it by typing an exclamation point (
!) followed by the command number, followed by the modification. For example, to modify the fourth command in your history and re-execute it, you would type:
!4 = sudo apt update
sudo apt upgrade
6 Tips for using the bash history command
- Use the
historycommand regularly to get a sense of the commands you use most frequently.
- Use the
lastcommand by typing
- Use the search function to quickly find specific commands in your history.
- Take advantage of the re-execution features to save time by reusing previous commands.
- Modify previous commands to save time and effort when you need to make small changes to a command.
- Enable the
HISTCONTROLenvironment variable to control the behavior of your bash history. For example, you can use
HISTCONTROL=ignorespaceto prevent commands that start with a space from being saved to the history.