如何扩充PS1? [英] How to expand PS1?

查看:90
本文介绍了如何扩充PS1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在多个目录中运行相同命令的shell脚本( fgit ).对于每个目录,我希望它显示当前提示+将在此处运行的命令.如何获得与解码的(扩展的)PS1相对应的字符串?例如,我的默认PS1是

I have a shell script that runs the same command in several directories (fgit). For each directory, I would like it to show the current prompt + the command which will be run there. How do I get the string that corresponds to the decoded (expanded)PS1? For example, my default PS1 is

${debian_chroot:+($debian_chroot)}\[\e[1;32m\]\u\[\e[0m\]@\[\e[1;32m\]\h\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]$(__git_ps1 ' (%s)')$

,我想回显生成的提示username@hostname:/path$,最好(但不一定)使用漂亮的颜色.粗略地看一下Bash手册并没有给出明确的答案,echo -e $PS1只评估颜色.

and I'd like to echo the resulting prompt username@hostname:/path$, preferably (but not necessarily) with the nice colors. A cursory look at the Bash manual didn't reveal any definite answer, and echo -e $PS1 only evaluates the colors.

推荐答案

从Bash 4.4开始,您可以使用@P扩展名:

Since Bash 4.4 you can use the @P expansion:

首先,我使用read -r和带引号的here-doc将您的提示字符串放入变量myprompt中:

First I put your prompt string in a variable myprompt using read -r and a quoted here-doc:

read -r myprompt <<'EOF'
${debian_chroot:+($debian_chroot)}\[\e[1;32m\]\u\[\e[0m\]@\[\e[1;32m\]\h\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]$(__git_ps1 ' (%s)')$ 
EOF

要打印提示(如果是PS1,则会被解释),请使用扩展名${myprompt@P}:

To print the prompt (as it would be interpreted if it were PS1), use the expansion ${myprompt@P}:

$ printf '%s\n' "${myprompt@P}"
gniourf@rainbow:~$
$

(实际上,有些\001\002字符来自\[\],您在这里看不到这些字符,但是如果您尝试编辑此帖子,则可以看到它们;您可以如果您键入命令,也会在终端上看到它们.)

(In fact there are some \001 and \002 characters, coming from \[ and \] that you can't see in here, but you can see them if you try to edit this post; you'll also see them in your terminal if you type the commands).

要摆脱这些缺陷,丹尼斯·威廉姆森在bash邮件列表上发送的窍门是使用read -e -p,以便这些字符可以由readline库解释:

To get rid of these, the trick sent by Dennis Williamson on the bash mailing list is to use read -e -p so that these characters get interpreted by the readline library:

read -e -p "${myprompt@P}"

这将提示用户,并正确解释myprompt.

This will prompt the user, with the myprompt correctly interpreted.

对于本文,Greg Wooledge回答说,您也可以从字符串中删除\001\002.可以这样实现:

To this post, Greg Wooledge answered that you might as well just strip the \001 and \002 from the string. This can be achieved like so:

myprompt=${myprompt@P}
printf '%s\n' "${myprompt//[$'\001'$'\002']}"

对于这篇文章,切特·拉米(Chet Ramey)回答说,您也可以完全关闭set +o emacs +o vi的行编辑功能.所以这也可以做到:

To this post, Chet Ramey answered that you could also turn off line editing altogether with set +o emacs +o vi. So this will do too:

( set +o emacs +o vi; printf '%s\n' "${myprompt@P}" )

这篇关于如何扩充PS1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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