How to Use the history Command in Ubuntu to Find Previously Typed Commands

Working in the Ubuntu Linux terminal requires typing complex, syntax-heavy commands. Often, you will spend five minutes crafting the perfect grep search or constructing a lengthy rsync command to backup a server, execute it successfully, and then move on. A week later, you realize you need to run that exact same complex command again, but you cannot remember the specific flags or file paths you used.

Instead of relying on your memory or searching the internet to rebuild the command from scratch, you can leverage one of the most powerful utilities in the Linux environment: the history command.

By default, the Bash shell in Ubuntu secretly records every single command you type into the terminal and saves it to a hidden text file (~/.bash_history). The history command allows you to view, search, and instantly re-execute this archive.

This guide explains how to use the history command in the Ubuntu terminal.

Viewing Your Command History

The most basic usage of the tool is to simply dump your recent activity onto the screen.

  1. Open your terminal application.
  2. Type the following command and press Enter:
    history

The terminal will print a numbered list of the last several hundred commands you have executed. The command at the very bottom of the list is the most recent. The numbers next to each command are extremely important, as they act as an index you can use for quick execution.

Executing a Command from History

If you see the command you want to run again in the list, you do not need to highlight it, copy it, and paste it. You can execute it instantly using its index number and an exclamation point (known as a “bang”).

For example, if you ran history and saw this output:

  492  sudo apt update
  493  sudo apt upgrade -y
  494  systemctl restart nginx

To run the exact systemctl restart nginx command again, you would simply type:

!494

Press Enter, and Ubuntu will immediately fetch command #494 from your history and execute it as if you had typed it manually.

Searching Your History

Scrolling through hundreds of lines of text to find a command from two weeks ago is inefficient. Instead, you can search your history using the grep tool.

For example, if you know you ran a complex scp (secure copy) command recently but cannot remember the exact IP address, you can search your history specifically for the word “scp”:

history | grep scp

The terminal will filter the output and only display commands that include “scp”. You can then find the index number of the correct command and execute it using the !number syntax.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.