为什么我的bash提示没有正确转义?

时间:2013-04-17 11:04:25

标签: bash command-prompt

我有以下bash提示变量,在我的.basrhc文件中定义:

PS1='\u@\h:\[\e[01;34m\] \[$(pwd|sed -e "s!.*/\\([^/]*/[^/]*/[^/]*\\)!\\1!g")\] \[\e[00m\] \[\e[01;31m\]\t\[\e[00m\]\$ '

从目录/ one / two / three / four /,这看起来像是一个彩色版本:

me@my-computer two/three/four 12:01:37$

(我不想把我得到的图像,但我是一个没有代表点的新人......)

我遇到了没有正确转义的问题(我认为这是源代码),当我向上滚动浏览历史记录时,这些行会截断bash提示符,并且终端不显示光标正确的命令行位置。在看到这种效果之前,您可能需要向上滚动几行。

我认为问题是sed命令,但如果这是正确的,我不知道如何解决它。
有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您可能希望设置PROMPT_DIRTRIM的值。它的工作方式与您想要的略有不同,但它可能足够接近,它内置于bash,并且使用起来要容易得多。 (注意:PROMPT_DIRTRIMbash 4.x的新内容(至少4.1,可能是4.0)。

PROMPT_DIRTRIM=3
PS1='\u@\h:\[\e[01;34m\] \w\[\e[00m\] \[\e[01;31m\]\t\[\e[00m\]\$ '

您还可以使用PROMPT_COMMAND变量简单地创建提示,方法是将其分解为可管理的步骤。如果bash不可用或不符合您的喜好,这将适用于早期版本的PROMPT_DIRTRIM

prompt_cmd () {
    # Trim leading directories off the current working directory.
    # Use single quotes so you don't need to escape the backslashes.
    trimmed_pwd=$( pwd | sed -e 's!.*/\([^/]*/[^/]*/[^/]*\)!\1!g' )

    # The initial part of your prompt
    PS1='\u@\h:\[\e[01;34m\] '
    # Add the directory; no single quotes, so the parameter expands, and
    # no need to wrap it in \[ \]
    PS1+=$trimmed_pwd
    # And the final part of your prompt
    PS1+='\[\e[00m\] \[\e[1;31m\]\t\[\e[00m\]\$ '
}
PROMPT_COMMAND='prompt_cmd'

答案 1 :(得分:0)

在sed命令中单引号和一点简单的正则表达式似乎有效。提示和颜色的东西我不知道,希望这有帮助。

sed 's!..*/\(.*/.*/.*\)!\1!g'