0
0
Linux CLIscripting~5 mins

History command and search in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you forget the exact command you typed before or want to repeat a previous command quickly. The history command helps you see past commands, and searching lets you find the one you need without scrolling through everything.
When you want to repeat a command you ran earlier without retyping it all.
When you need to find a command you used days ago but don’t remember exactly how it looked.
When you want to check what commands you or someone else ran on the system.
When you want to save time by reusing complex commands from your history.
When you want to search for commands related to a specific task or keyword.
Commands
This command shows a numbered list of all the commands you have typed in the current shell session and previous ones saved in the history file.
Terminal
history
Expected OutputExpected
1 ls -l 2 cd /var/log 3 cat syslog 4 history
This command searches your command history for any commands containing the word 'git'. It helps you find specific commands quickly.
Terminal
history | grep git
Expected OutputExpected
15 git status 23 git commit -m 'fix bug' 42 git push origin main
Pressing Ctrl + r starts a reverse search in your command history. You can type part of a command, and it will show the most recent match. Press Enter to run it or Ctrl + r again to find earlier matches.
Terminal
Ctrl + r
Expected OutputExpected
(reverse-i-search)`git': git push origin main
This runs the command numbered 42 from your history list. It saves time by letting you rerun a command without typing it again.
Terminal
!42
Expected OutputExpected
Everything pushed to origin main branch
Key Concept

If you remember nothing else from this pattern, remember: the history command and reverse search let you quickly find and reuse past commands without retyping.

Common Mistakes
Trying to run ! without a number or valid command reference
The shell will give an error because it doesn't know which command to run.
Use ! followed by a valid history number or command prefix, like !42 or !git.
Not pressing Ctrl + r to start reverse search and instead scrolling manually
Manually scrolling through history is slow and inefficient.
Use Ctrl + r and type part of the command to quickly find it.
Using history without piping to grep when searching for a specific command
You get a long list and have to look through everything manually.
Use history | grep keyword to filter commands by keyword.
Summary
Use the history command to list all past commands with numbers.
Use history | grep keyword to search commands containing a specific word.
Use Ctrl + r to interactively search and reuse previous commands quickly.
Use !number to rerun a command from the history list by its number.