Bash is a common shell environment and most Linux distributions also come with Bash, so using history efficiently can save the time of manually typing repetitive commands. In this article, I share a few tips and configurations that I use myself.
This technique should be more or less known to everyone, that is, press
Ctrl-R in the input screen to search, the returned result is the latest matching command, and then press enter to execute.
But sometimes the search results are only very similar to what I want, but not exactly the same, I want to be able to make small changes to the command before execution, so how? In fact, at this time, press Esc to exit and edit.
Another way is to use
:p, which means print but not execute in Bash, so if we want to see a command with a certain prefix, we can use
!prefix:p to print it.
HISTIGNORE is an environment variable that instructs Bash what commands not to add to history, for example a variable like this.
It is possible to remove meaningless interactive commands from the HISTORY. If you often use abbreviations like
la, it might be a good idea to add them to HISTIGNORE.
HISTCONTROL is also an environment variable, and it has a few options
- ignorespace: all commands that start with a space are not added to HISTORY
- ignoredups: duplicate commands will not be added to the history
- ignoreboth: turns on both of the above features
Usually some distributions already come with the ignoredups option, so if you want to avoid some specific commands to be counted in history, then you can turn on the ignorespace option.
History problem between parallel windows
I believe many students will have this problem. When managing servers remotely, we usually use various window multiplexing tools, such as
screen, in order to monitor certain tasks or time-consuming tasks without blocking human operations, so since Bash writes history to the
.bash_history file only when it is closed, then Most of the time when we close these windows, only the history of the last closed window is recorded.
We can use
to instruct Bash to append the history to the original history instead of overwriting it.
Use ! to execute the commands in the history
! can be used to execute commands, e.g.
!10 is to execute the 10th command in the history. Of course, you can also execute the most recent command, for example
!-3 is the third last command.
Here you can also use it in combination with
:p to avoid the risks associated with direct execution.
If you must avoid all the risks and want to check the command each time before executing it, and don’t want to type
:p, then Bash has another option to do that:
shopt -s histverify. This option will make all commands executed with ! command will require you to press Enter to confirm before it will execute.
Use the parameters of the previous command
!* will fill in the last argument of the previous command and all arguments to this position, respectively, e.g.