快速参考

与历史的互动

# List all previous commands
history

# Clear the history, useful if you entered a password by accident
history -c

活动指示人

# Expands to line n of bash history
!n

# Expands to last command
!!

# Expands to last command starting with "text"
!text

# Expands to last command containing "text"
!?text

# Expands to command n lines ago
!-n

# Expands to last command with first occurrence of "foo" replaced by "bar"
^foo^bar^

# Expands to the current command
!#

单词指示符

这些由:与他们所指的事件指示符分开。如果单词指示符不以数字开头,则可以省略冒号:!^!:^相同。

# Expands to the first argument of the most recent command
!^

# Expands to the last argument of the most recent command (short for !!:$)
!$

# Expands to the third argument of the most recent command
!:3

# Expands to arguments x through y (inclusive) of the last command
# x and y can be numbers or the anchor characters ^ $
!:x-y

# Expands to all words of the last command except the 0th
# Equivalent to :^-$
!*

修饰符

这些修改了前面的事件或单词指示符。

# Replacement in the expansion using sed syntax
# Allows flags before the s and alternate separators
:s/foo/bar/ #substitutes bar for first occurrence of foo
:gs|foo|bar| #substitutes bar for all foo

# Remove leading path from last argument ("tail")
:t

# Remove trailing path from last argument ("head")
:h

# Remove file extension from last argument
:r

如果 Bash 变量 HISTCONTROL 包含 ignorespaceignoreboth(或者,HISTIGNORE 包含模式 [ ]*),则可以通过在空格前添加命令来阻止命令存储在 Bash 历史记录中:

# This command won't be saved in the history
 foo

# This command will be saved
bar