History command on Linux (command history)
The history command is used to list the contents of the ~/. bash_history of the logged in user, and lists the command history lines.
The “~” is a Linux shortcut for HOME directory of the logged in user.
You can pass as a parameter the number of lines you want it to show since the last command entered:
You can also use history with grep to filter commands:
When you know the line number you want to use again, simply add an exclamation followed by the corresponding line number:
The history command has a few options, namely:
- -c Clear the history list
- -d x Delete the number line x
- -a & nbsp; Adds the commands from the current bash session to the history file
Bash also offers other possibilities for working with the command history:
Shortcut | Description |
!! | Execute the last command typed |
!n | Run the command on line **n** in the .bash\_history file |
!text | Run the most recent command that starts with the **text** |
!?text | Run the most recent command that contains the **text** |
^text1^text2 | Run the last command changing **text1** to **text2** |
Alt M < | Go to the beginning of the file .bash\_history |
Alt M > | Go to the end of the file .bash\_history |
Ctrl p | Retrieve the commands stored in the file .bash\_history from back to front |
Ctrl n | Retrieve the commands already listed from front to back |
Ctrl b | Return a character to the commands already retrieved |
Ctrl f | Go one character Forward on the commands already retrieved |
Ctrl a | Return to the beginning of the line in the commands already recovered |
Ctrl and | Go to the end of the line in the commands already recovered |
Ctrl l | Clear the screen |
Ctrl d | Delete characters from the text of cursor to the end of the line |
Ctrl k | Delete the cursor text to the end of the line at once |
Ctrl y Paste | the text deleted by the previous command on the screen |
Ctrl rtext | Search for commands containing the text from the last command to the first |
Ctrl stext | Search for commands that contain the text from the first command to the last |
A very practical use of the command history is the double exclamation**!!** , which executes the last command typed, especially when it is necessary to re-execute the command with superuser powers with the command “sudo“:
In this example, an attempt was made to install the lynx package, but apt wouldn’t let it because only root can install software.
To solve the issue, you can simply use sudo with the !!