为什么我的bash提示无法正确转义? [英] why isn't my bash prompt properly escaping?

查看:117
本文介绍了为什么我的bash提示无法正确转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following bash prompt variable, defined in my .basrhc file:

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

在目录/ one / two / three / four /中,这看起来像就像彩色版本:

From a directory, /one/two/three/four/, this would look like a colourised version of:

me @ my-computer两/三/四12:01:37 $

(我不愿透露自己所得到的图像,但我是新人,没有代表点。)

(I wan't to put an image of what I get, but I'm a newcomer with no rep points..)

我有一个问题,那就是它不能正确地转义(我认为这是源头),因为在我的历史记录中向上滚动时,这些行会截断bash提示符,并且终端不会显示将光标放在命令行的正确位置。在看到这种效果之前,您可能需要向上滚动几行。

I'm having problems with it not being escaped properly (I think this is the source) in that, when scrolling up through my history, the lines truncate the bash prompt, and the terminal doesn't display the cursor in the correct place of the command line. You may have to scroll up a fair few lines before this effect is seen though.

我认为问题在于 sed 命令,但不确定是否正确。

有什么想法吗?

I think the problem is the sed command but I'm not sure how to resolve it if that's right.
Any thoughts?

推荐答案

您可能想要设置 PROMPT_DIRTRIM 的值。它的工作原理与您想要的略有不同,但是它可能已经足够接近了,它内置在 bash 中,并且使用起来更加容易。 (注意: PROMPT_DIRTRIM bash 4.x的新功能(至少为4.1,可能为4.0)。)

You might want to set the value of PROMPT_DIRTRIM instead. It works slightly differently from what you want, but it's probably close enough, it's built-in to bash, and it's a lot easier to use. (Note: PROMPT_DIRTRIM is new to bash 4.x (at least 4.1, possibly 4.0)).

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

您还可以使用 PROMPT_COMMAND 变量简单地通过将提示分为可管理的步骤来创建提示。如果 PROMPT_DIRTRIM 不可用或不符合您的喜好,这将在 bash 的早期版本中起作用。

You can also make use of the PROMPT_COMMAND variable to simply creating your prompt by breaking it into manageable steps. This will work in earlier versions of bash, if PROMPT_DIRTRIM isn't available or isn't to your liking.

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'

这篇关于为什么我的bash提示无法正确转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆