Linux 命令行和 Bash Shell 快捷方式
尽管您可能认为您已经学会使用 bash shell 掌握 Linux 命令行,但总有一些新技巧需要学习,以使您的命令行技能更加高效。本文将教您一些更基本的技巧,让您的 Linux 命令行和 bash 生活变得更容易忍受,甚至更愉快。
本节将主要讨论 bash 快捷方式与三个 bash 历史扩展字符“!”、“^”和“#”的组合。 Bash 命令历史扩展字符“!”表明历史扩展的开始。 “^”是一个替换字符,用于修改先前运行的命令。最后一个可选字符是“#”,表示该行作为注释的提醒。
重复上一个命令
$ echo Bash Shortcuts
Bash Shortcuts
$ !!
echo Bash Shortcuts
Bash Shortcuts
!! 可能是最简单和最流行的 bash 快捷方式,它只是显示并执行您最后输入的命令。
重复最近的命令
$ echo Bash Shortcuts
Bash Shortcuts
$ wc -m /etc/bash_completion
45 /etc/bash_completion
$ !echo
echo Bash Shortcuts
Bash Shortcuts
输入“!”字符后跟关键字将指示shell搜索以关键字开头的最新命令。可以对前一个命令进行较小的修改,以便只打印最近的命令而不执行它。如果您不确定最近的命令是什么并且不想在确认其含义之前执行它,这会非常方便。为此,只需在命令末尾添加 :p ,然后添加 !!如果您乐意执行它:
$ echo Bash Shortcuts
Bash Shortcuts
$ wc -m /etc/bash_completion
45 /etc/bash_completion
$ !echo:p
echo Bash Shortcuts
$ !!
echo Bash Shortcuts
Bash Shortcuts
最后一个命令的所有参数
$ echo Bash Shortcuts
Bash Shortcuts
$ touch !*
touch Bash Shortcuts
$ ls
Bash Shortcuts
!* 快捷方式将扩展到最后一个命令使用的所有参数。在上面的示例中,我们使用了 echo 命令使用的所有先前参数来使用具有相同参数的 touch 命令创建文件。
最后一个命令的第一个参数
$ echo Bash Shortcuts
Bash Shortcuts
$ touch !^
touch Bash
$ ls
Bash
与前面的示例类似,在此示例中,我们使用 bash 快捷方式 !^ 仅重用最后一个命令的第一个参数。
最后一个命令的最后一个参数
echo Bash Shortcuts
Bash Shortcuts
$ touch !$
touch Shortcuts
$ ls
Shortcuts
与前面的示例相同,我们也可以重用提供给先前运行的命令的最后一个参数。
快速命令替换
在下面的示例中,我们将重新运行前面的命令,但用“bash”替换单词“linux”。
$ echo linux command line linux command line
linux command line linux command line
$ ^linux^bash^
echo bash command line linux command line
bash command line linux command line
上面的示例将第一次出现的关键字 Linux 替换为 bash。这相当于:
$ !!:s/linux/bash/
执行历史中的第n条命令
默认情况下,bash shell 会跟踪您之前执行过的所有命令作为历史记录。 bash 历史记录中的每个命令都有其相关的编号。以下示例将执行 bash 命令历史记录中的第 189 个命令。
$ !189
与前面的示例类似,您可以先使用 :p 打印它,而不是直接执行命令。
$ !189:p
提示:要查看 bash 命令历史记录中的最后 5 个命令,请执行:$History 5
要执行 bash 历史记录中的最后 4 个命令,请使用减量 -4:
$ !-4
重复整个命令行
$ echo bash command line !#
echo bash command line echo bash command line
bash command line echo bash command line
!# 使 bash 在执行命令时重复您在整个命令行中键入的所有内容。您可以通过仅使用 :nth 关键字打印某些关键字来限制此行为。例如,要仅重新打印第二个关键字,您可以使用:
$ echo bash command line !#:2
echo bash command line command
bash command line command
基本 Bash 命令行编辑快捷方式列表
CTRL + f | Move forward one word |
CTRL + b | Move backward one word |
ALT + c | Capitalize current character at the cursor and move to the end of the word |
ALT + u | Make all characters uppercase starting from the current cursor position to the end of the word |
ALT + l | Make all characters lowercase starting from the current cursor position to the end of the word |
ALT + d | Delete all characters starting from the current cursor position to the end of the word |
ALT + f | Move forward word by word |
ALT + t | Swap current word with previous |
CTRL + t | Swap current character with previous |
CTRL + k | Delete all from current cursor position to the end of the command line |
CTRL + y | Paste text or characters previously deleted with deletion shortcuts |
本文的目的是介绍 Linux 命令行上使用的一些基本 bash 快捷方式。如需进一步阅读,请访问 bash 和历史记录的手册页:
$ man bash
$ man history