\ [和\]之间的转义ANSI非打印字符序列

时间:2018-09-23 11:43:41

标签: bash prompt

bash manual说,在提示符下,任何非打印字符序列都应括起来,例如:\[this\]

\[  Begin a sequence of non-printing characters.
    This could be used to embed a terminal control sequence into the prompt.

\]  End a sequence of non-printing characters.

给出提示中要包含的字符串,我如何自动转义所有ANSI控制/颜色代码,以使提示在所有情况下都能正确显示/换行?


区别:在这里,我假设已经产生了带有ANSI控制代码的字符串。

This related question假定可以通过编辑字符串的生成函数来插入定界符。

2 个答案:

答案 0 :(得分:0)

以下内容将ANSI控制序列括在ASCII SOH^A)和STX^Bwhich are equivalent to \[ and \] respectively中:

function readline_ANSI_escape() {
  if [[ $# -ge 1 ]]; then
    echo "$*"
  else
    cat  # Read string from STDIN
  fi | \
  perl -pe 's/(?:(?<!\x1)|(?<!\\\[))(\x1b\[[0-9;]*[mG])(?!\x2|\\\])/\x1\1\x2/g'
}

使用方式:

$ echo $'\e[0;1;31mRED' | readline_ANSI_escape

或者:

$ readline_ANSI_escape "$string"

作为奖励,多次运行该函数不会重新转义已经转义的控制代码。

答案 1 :(得分:0)

不要尝试使其自动化。

Bash要求您手动添加\[...\]的原因是因为shell无法合理地知道任何给定的终端将如何解释任何转义码。如果是这样,那么Bash只会首先做到这一点。

例如,以下是其他答案无法处理的许多情况。在每种情况下,我的特定终端上都没有输出输出,但是转义功能无法转义它们:

printf '\e]1;Hello\a'  # Set window title
printf '\e[0;2;0;0;0}' # 24-bit color
printf '\e[13]'        # Unblank screen
相关问题