The command history in Linux is a powerful feature that allows users to view and recall previously executed commands. It can help save time by avoiding the need to retype long or complex commands. In this blog post, we will explore some useful techniques for working with command history in the Bash shell.
Viewing Command History
To view the command history in Bash, you can use the history
command. Simply type history
and press Enter to see a list of previously executed commands, along with their corresponding line numbers.
$ history
1 ls
2 mkdir new_directory
3 cd new_directory
...
Executing Commands from History
To execute a command from the command history, you have a few options:
-
Using the up arrow key: Pressing the up arrow key (
↑
) will cycle through previously executed commands. Once you find the desired command, press Enter to execute it. -
Using the
!!
syntax: Typing!!
and pressing Enter will execute the most recent command from the history. -
Using
!n
syntax: If you know the line number of the command in the history, you can execute it by typing!n
and pressing Enter. Replacen
with the specific line number.
$ !3 # Executes the command on line 3 in the history
Searching Command History
To search for a specific command in the command history, you can use the Ctrl + R
keyboard shortcut. This will open a reverse search prompt where you can start typing the keywords of the command you’re looking for. Bash will search the command history as you type and display the closest match.
(reverse-i-search)`keyword': command-you-are-looking-for
Once you find the desired command, you can press Enter to execute it or use the right arrow key to edit it before execution.
Managing Command History
Bash provides several options for managing the command history:
-
Increasing history size: By default, Bash stores the last 500 commands in its history. You can increase this limit by modifying the
HISTSIZE
environment variable in your shell configuration file (e.g.,.bashrc
or.bash_profile
). -
Ignoring duplicates: Bash includes duplicate commands in its history. To ignore duplicate commands, you can set the
HISTCONTROL
variable toignoredups
in your shell configuration file. -
Ignoring specific commands: You can exclude specific commands from being recorded in the history by prefixing them with a space character. These commands will not be stored in the history.
Conclusion
The command history in the Bash shell is a valuable tool for improving productivity and simplifying command execution. By utilizing the techniques discussed in this blog post, you can easily recall and execute previously executed commands in Linux. Whether you prefer using keyboard shortcuts, the !!
syntax, or the Ctrl + R
search functionality, mastering command history can save you time and effort on the command line.