Bash提示多命令替换 [英] Bash prompt multiple command substitution
问题描述
我正在使用以下(简化的)函数在.bashrc中设置我的bash提示符:
I am setting up my bash prompt in .bashrc using the following (simplified) function:
set_prompts() {
PS1="\u@\h in \w "
PS1+="\$(get_git_repo_details)"
PS1+="\n"
PS1+="\$(exit_status_prompt)"
}
现在,根据 $?
的值是否为0, exit_status_prompt
将打印不同的彩色提示字符.
Now the exit_status_prompt
prints a different coloured prompt character, depending on whether the value of $?
is 0 or not.
我注意到的是,使用上面的代码,提示字符的颜色从不更新.但是,如果在将 get_git_repo_details
的输出附加到 $ PS1
之前,将 exit_status_prompt
的输出附加到 $ PS1
,或者不附加 get_git_repo_details
,然后会更新.
What I noticed though, is that with the code as above, the colour of the prompt character never updates. However, if I append the output of exit_status_prompt
to $PS1
before I append the output of get_git_repo_details
, or don't append the output of get_git_repo_details
at all, then it does update.
有人知道是什么原因造成的吗?谢谢.
Does anyone know what is causing this? Thanks.
exit_status_prompt()
{
if [ $? -ne 0 ]
then
highlight 1 "❯ "
else
highlight 2 "❯ "
fi
}
然后, highlight
函数仅使用 tput
在第二个参数中的字符串前加上第一个参数中指定的颜色.
The highlight
function then just uses tput
to prepend the string in the second parameter with the colour specified in the first parameter.
推荐答案
您需要先调用 exit_status_prompt
,然后再执行 set_prompts
或 $?
将被重置.大概, exit_status_prompt
使用最近执行的命令或赋值的退出状态.
You need to call exit_status_prompt
before doing anything else in set_prompts
, or $?
is going to be reset. Presumably, exit_status_prompt
uses the exit status of the most recently executed command or assignment.
set_prompts() {
esp=$(exit_status_prompt)
PS1="\u@\h in \w "
PS1+="$(get_git_repo_details)"
PS1+="\n"
PS1+="$esp"
}
我已经取消了命令替换,因为我假设您正在(并且应该)运行 set_prompts
作为 PROMPT_COMMAND
中的第一条命令.
I've unescaped the command substitutions, because I assume that you are (and should be) running set_prompts
as the first command in PROMPT_COMMAND
.
这篇关于Bash提示多命令替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!