.bash_history
The .bash_history
file is a hidden file located in the home directory of a user. It stores the command history of Bash shell sessions. Each line in the file represents a command that the user has entered in the Bash shell, and it allows the user to recall and reuse previous commands easily.
Location and Viewing
The .bash_history
file is typically located in the home directory of a user:
To view the contents of the .bash_history
file, you can use commands such as cat
, less
, more
, or tail
:
or
Understanding the Contents
Each line in the .bash_history
file corresponds to a command that was executed in the Bash shell. For example:
Managing .bash_history
.bash_history
Viewing History in Bash
To view your command history directly within a Bash session, you can use the history
command:
Clearing History
If you want to clear the command history for the current session and also clear the .bash_history
file, you can use the following commands:
history -c
: Clears the current session’s command history.> ~/.bash_history
: Truncates the.bash_history
file to zero length, effectively clearing it.
Appending History to File
By default, the command history is written to the .bash_history
file when a Bash session exits. To immediately append the current session’s command history to the .bash_history
file, use:
Reloading History
If you have modified the .bash_history
file and want to reload it into the current session, use:
Customizing History Behavior
You can customize how Bash handles command history by setting environment variables in your ~/.bashrc
file.
HISTSIZE
HISTSIZE
Sets the number of commands to remember in the command history for the current session:
HISTFILESIZE
HISTFILESIZE
Sets the maximum number of lines contained in the history file:
HISTIGNORE
HISTIGNORE
Defines patterns for commands that should be excluded from the history. Multiple patterns are separated by colons (:
):
This example ignores the ls
, cd
, and exit
commands.
HISTCONTROL
HISTCONTROL
Controls what is saved on the history list. Options include ignoredups
(ignore duplicate commands) and ignorespace
(ignore commands that start with a space):
Practical Use Cases
Auditing Commands
The .bash_history
file is useful for auditing the commands that were run on a system. You can review the file to see what actions were performed in previous sessions.
Reusing Complex Commands
When you need to reuse complex commands or a sequence of commands, you can find them in your history and execute them again, saving time and avoiding retyping.
Conclusion
The .bash_history
file is an essential component of the Bash shell that helps users keep track of their command history. By understanding how to manage and customize the command history, you can improve your efficiency and productivity in the terminal.
Last updated