history Command in Linux
Overview
The history command in Linux is a powerful tool that allows users to view and manipulate previously executed commands. It enables users to save time and effort by quickly retrieving and re-executing past commands without having to retype them manually.
Linux history Command Syntax
The syntax for the history command is as follows:
Where:
- options: These are the optional flags that can be used with the history command to modify its behavior.
history Command Options:
- -c: Clears the history list by deleting all the entries.
- -d OFFSET: Deletes the history entry at the specified offset.
- -w [FILENAME]: Writes the current history to the file specified or the default history file if no filename is given.
- -r [FILENAME]: Reads the history file and appends its content to the current history list.
Example Usages
-
Display the command history:
Output:
Explanation: This command lists all the commands executed previously in the current shell session, with a unique command number preceding each command.
-
Execute the most recent command:
Output:
Explanation: This command re-executes the most recent command in the history list, which in this case is 'pwd'.
Tips
-
Use the 'history | grep keyword' combination to search for specific commands in the history list.
-
Press the 'Up Arrow' key to cycle through previous commands, making it easier to find and re-execute them.
Advanced Use Cases of history Command in Linux
-
Execute a specific command from the history list:
Output:
Explanation: This command re-executes the command with the specified number (2 in this case) from the history list.
-
Execute the most recent command starting with a specific string:
Output:
Explanation: This command re-executes the most recent command in the history list that starts with the specified string 'ls'.
-
Display a specific range of history entries:
Output:
Explanation: This command displays the history entries within the specified range (from 2 to 4 in this case).
Conclusion
-
The history command helps users quickly access and re-execute previously executed commands.
-
Options like -c, -d, -w, and -r allow users to modify the behavior of the history command.
-
Advanced usages include executing specific commands from the history list or displaying a range of history entries.