bash提示:高亮输入的命令

bash prompt: highlight command being entered

在 bash 上输入命令如下:

<Prompt $>  <The Command I Entered>
<Output Of The Command>

我正在寻找使 The Command I Entered 变粗的方法。 通过将 tput bold 放入 PS1.

可以很容易地从提示开始加粗

然而问题是,如何在按下 Entertput sgr0 它。 我可以使用 readline / bash 魔法来实现这个吗?

前 Bash 4.4:

在 bash 4.3.x(可能更早)中,"debug trap" 在命令行命令执行之前执行。

trap 'tput sgr0' DEBUG

但这有一个缺点:它在每个执行的简单命令之前执行。所以如果你 运行:

$ echo Hello && echo World 

调试陷阱被调用了两次。

那么下面的命令将不会按预期工作:

tput setaf 1 ; echo "This is red"

打印出来的"This is red"不会是红​​色的

DEBUG trap and PROMPT_COMMAND in Bash and also the accepted answer to this question

Bash 4.4

在Bash 4.4 中引入了变量$PS0。这是引自 man page:

The value of this parameter is expanded (see PROMPTING below) and displayed by interactive shells after reading a command and before the command is executed.

因此,对于 bash 4.4,您可以执行以下操作:

PS0="\[$(tput sgr0)\]"

\[\]用于包含不可打印的字符(此处为终端控制序列以重置文本属性)。我不确定 PS0 是否真的需要这样做,但这不会有什么坏处。 shell 两种方式的输出都没有视觉差异。

要扩展 使 bash 中的命令 加粗 4.4+ 需要设置 PS1PS0 像这样:

PS1="\[\e[32m\]\u@\h \t \W \$\[\e[0;30;1m\] "
PS0="\[$(tput sgr0)\]"

显然您可能不喜欢我无聊的提示,但它为您提供了粗体命令的起点。 \[\e[0;30;1m\] 将命令设置为以黑色文本和粗体显示。其他 color choices 可能更适合你。

我发现这在使用 asciinema to capture examples for documentation. It reminds me of the O'Reilly style 包括 UNIX 控制台示例和粗体命令时很方便。