Maximize your efficiency in the terminal with these handy Bash history commands and shortcuts. Quickly access, search, and rerun commands like a pro.
Contents
Basic History Commands
- View Command History:
history
- Displays your recent command history with line numbers.
- Clear Command History:
history -c
- Clears your current session’s command history.
Re-executing Commands
- Execute Last Command:
!!
- Immediately rerun the most recent command.
- Execute Command by Number:
!number
- Rerun a command by its history number (e.g.,
!42
).
- Rerun a command by its history number (e.g.,
- Execute Last Command Starting with…:
!string
- Rerun the most recent command starting with
string
(e.g.,!ls
).
- Rerun the most recent command starting with
- Reverse Search:
ctrl+r
- Dynamically search through command history as you type. Press
ctrl+r
again to search further back.
- Dynamically search through command history as you type. Press
- Navigate Using Arrow Keys:
- Use the up and down arrow keys to scroll through previously executed commands.
Editing Before Re-executing
- Edit Last Command Before Running:
fc
- Opens the last command in your default editor for modifications before executing.
- Edit Specific Command by Number:
fc number
- Edit a command by its history number in your default editor (e.g.,
fc 42
).
- Edit a command by its history number in your default editor (e.g.,
Tips for Efficient History Use
- Increase History Size: If you find yourself needing more history, you can increase the size by adding the following lines to your
~/.bashrc
or~/.bash_profile
:HISTSIZE=10000 HISTFILESIZE=20000
- Secure Your History: Be cautious with sensitive information in commands, especially when using
sudo
. History commands can be inadvertently rerun. - Customize and Extend: Bash history is highly customizable. Explore
HISTCONTROL
,HISTIGNORE
, and other environment variables for a tailored experience.
Final Thoughts
Leveraging the power of Bash history enhances your command line efficiency and saves time. Whether you’re a beginner or an experienced user, these commands and shortcuts are invaluable tools in your arsenal.