了解PS1环境变量

Dom*_*que -1 linux prompt ubuntu environment-variables windows-subsystem-for-linux

在 Stackoverflow 上,我刚刚看到一个有关PS1环境变量的问题,该变量负责 Linux 终端提示符。

我的提示如下:

username@PORT-usr:/dir
Run Code Online (Sandbox Code Playgroud)
  • username是我登录 WSL 时使用的用户名。
  • PORT-usr是我的笔记本电脑的名称。
  • /dir是我当前的目录。

我的PS1环境变量如下所示:

Prompt>echo $PS1
\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$
Run Code Online (Sandbox Code Playgroud)

尝试执行此操作不起作用:

Prompt>echo $($PS1)
\[\e]0;\u@\h:: command not found

Prompt>echo echo $(\[\e]0;\u@\h: \w\a\]${debian_chroot...)
e]0: command not found
u@h:: command not found
32m]u@h[033[00m]:[033[01: command not found
34m]w[033[00m]$: command not found
Run Code Online (Sandbox Code Playgroud)

使用的变量的语法是什么?$PS1我可以使用什么命令来学习理解该语法?

tel*_*coM 6

shellPS1变量(可能是也可能不是环境变量)不包含常规 shell 命令。它使用特定于您所使用的各种 shell 的特殊过程扩展为提示符。它可能包含普通命令无法识别的特殊序列echo

您的 shell 提示符看起来像 Debian(以及可能相关的发行版)的默认提示符。Debian 对于普通用户帐户的默认 shell 是bash,因此您应该查看Bash 参考手册的6.9PROMPTING控制提示符一章。man bash

要了解任何嵌入式终端控制代码,您可能还必须参考终端仿真器的相应文档,例如Xterm 控制序列的参考

以下是当前提示的解释方式:

\[ ... \]     encapsulates any terminal control codes that will not result in
              any visible output on the prompt line

\e]0;         Xterm control code to set terminal window title and icon name
\u@\h: \w     expands to window title <username>@<hostname>: <workdir>
\a            indicates the end of terminal window title / icon name string
\]            end of encapsulation

${debian_chroot:+($debian_chroot)}
              if variable $debian_chroot is defined, adds text
              "(<contents of $debian_chroot>)" to the prompt

\[            encapsulates terminal control codes, see above
\033[01;32m   set bold output with green foreground color
\]            end encapsulation

\u@\h         expands to "<username>@<hostname>" in the prompt

\[            encapsulates terminal control codes, see above
\033[00m      reset to normal output
\]            end encapsulation

:             outputs a ":" character

\[            encapsulates terminal control codes, see above
\033[01;34m   set bold output with blue foreground color
\]            end encapsulation

\w            outputs the current working directory

\[            encapsulates terminal control codes, see above
\033[00m      reset to normal output
\]            end encapsulation

\$            outputs "$" if a regular user, "#" when UID 0 (root)
Run Code Online (Sandbox Code Playgroud)

如果\[...\]非打印字符的封装没有正确完成,当命令行变得比终端的宽度长时,您将看到换行错误。