快速參考

與歷史的互動

# 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