Skip to content
Home » Recall and Reuse Previous Commands With Bash History

Recall and Reuse Previous Commands With Bash History

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 history command.

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:

!3

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:

!ls

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:s/old/new
!4 = sudo apt update
!4:s/update/upgrade
sudo apt upgrade

6 Tips for using the bash history command

  1. Use the history command regularly to get a sense of the commands you use most frequently.
  2. Use the last command by typing !!.
  3. Use the search function to quickly find specific commands in your history.
  4. Take advantage of the re-execution features to save time by reusing previous commands.
  5. Modify previous commands to save time and effort when you need to make small changes to a command.
  6. Enable the HISTCONTROL environment variable to control the behavior of your bash history. For example, you can use HISTCONTROL=ignorespace to prevent commands that start with a space from being saved to the history.

Leave a Reply

Your email address will not be published. Required fields are marked *

5 + 3 =