I used
history | less
to get the lines of previous commands and from the numbers on the left hand side I found the line I wanted repeated (eg. 22) and did
!22
at the command prompt and it worked — executing the set of commands on the line I did at that time. I cannot figure out where the exclamation mark is used, what does it represent in terms of actions taken by bash, and where to use it. From the documentation I do not see an explanation that is 'tangible'.
Best Answer
!
invokes history expansion, a feature that originally appeared in the C shell, back in the days before you could count on terminals to have arrow keys. It's especially useful if you add the current command number to the prompt (PS1="\!$ "
) so you can quickly look at your screen to get numbers for past commands.Now that you can use arrow keys and things like Ctrl-R to search the command history, I don't see much use for the feature.
One variant of it you might still find useful is
!!
, which re-executes the previous command. On its own, I don't find !!Enter any faster than just ↑ Enter, but it can be helpful when combined into a larger command.Example: A common pilot error on
sudo
based systems is to forget thesudo
prefix on a command that requires extra privileges. A novice retypes the whole command. The diligent student edits the command from the shell's command history. The enlightened one typessudo !!
.Processing
!
in this way is enabled in Bash by default in interactive shells and can be disabled withset +o histexpand
orset +H
. You can disable it in Zsh withset -K
.