是否有可能pre-评估在bash的PS1的值? [英] Is it possible to pre-evaluate a value in bash's PS1?

查看:108
本文介绍了是否有可能pre-评估在bash的PS1的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个Bash提示符这将有我的两个混帐分支信息(使用Git的bash的自动完成__git_ps1)和一个小的彩色笑脸,表示最近运行的命令是否成功。

I'm trying to build a Bash prompt which will have both my git branch information (using __git_ps1 from git's bash-completion) and a little colored smiley to indicate whether the most recently run command was successful.

的笑脸是使用这种技术,我发现这里的SO创建:

The smiley is created using this technique, which I found here on SO:

SMILEY="${GREEN}:)${COLOR_NONE}"
FROWNY="${RED}:(${COLOR_NONE}"
STATUS_EMOTICON="if [ \$? = 0 ]; then echo \"${SMILEY}\"; else echo \"${FROWNY}\"; fi"

下面的提示行我想用:

export PS1="[\t]${RED}[\u@$MACHINE:${BOLD_CYAN}\w${GREEN}\$(__git_ps1 ' %s')${RED}]${COLOR_NONE} \`${STATUS_EMOTICON}\`\n$ "

不幸的是,它看起来像由运行的程序__git_ps1覆盖 $?价值,我结束了与每一个表情是一个绿色的笑脸,甚至跑步后

Unfortunately, it looks like the programs that are run by __git_ps1 override the $? value, and I end up with every emoticon being a green smiley, even after running false.

取出__git_ps1电话...

Taking out the __git_ps1 call...

export PS1="[\t]${RED}[\u@$MACHINE:${BOLD_CYAN}\w${RED}]${COLOR_NONE} \`${STATUS_EMOTICON}\`\n$ "

...使表情正常工作。

...makes the emoticon work correctly.

所以我显然需要做的是评估 $ {STATUS_EMOTICON} 的运行 __ git_ps1 ,但包括的 __ git_ps1 的输出后的评估值的。这可能吗?

So what I apparently need to do is evaluate ${STATUS_EMOTICON} before running __git_ps1, but include the evaluated value after __git_ps1's output. Is that possible?

推荐答案

不要把 $(CMD)`cmd` 直接在 PS1 。相反,使用猛砸的 PROMPT_COMMAND 变种。我最常做的就是定义一个函数 _PS1_cmd 并设置 PROMPT_COMMAND = _PS1_cmd 。然后在 _PS1_cmd ,我设置其它瓦尔我想在 PS1 包含。例如:

Don't put $(cmd) or `cmd` directly in your PS1. Instead, use Bash's PROMPT_COMMAND var. What I usually do is define a function _PS1_cmd and set PROMPT_COMMAND=_PS1_cmd. Then in _PS1_cmd, I set misc vars I'd like to include in PS1. For example:

THE-OLD-PROMPT # cat prompt.rc
function _PS1_cmd()
{
    local saveExit=$?

    # This non-zero exit will not affect $? on command line
    g_git_ps1=$( echo TESTING; exit 1 )
    if (( saveExit )); then
        g_smiley=':('
    else
        g_smiley=':)'
    fi

    # Seems like this is not necessary, at least with bash 4.2.37. But
    # to be safe, always return it.
    return $saveExit
}

PROMPT_COMMAND=_PS1_cmd
PS1='$g_git_ps1 $g_smiley '
THE-OLD-PROMPT # source ./prompt.rc
TESTING :) ( exit 123 )
TESTING :( echo $?
123
TESTING :) echo $?
0
TESTING :)

这篇关于是否有可能pre-评估在bash的PS1的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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