0

My Bash prompt (based on mike kasberg's) generally works fine. But when I get an error code, and then write over to the next line, no newline is generated, so the text goes back over my previous prompt.

Screenshot to clarify.

Code in question:

    # gets error code
    __mkps1_inject_exitcode() {
        local code=$1
        local bg_red='\033[41m'
        local white='\033[37m'
        local red='\033[31m'
        if [ "$code" -ne "0" ]; then
            echo -e " ${bg_red}${white} 󰉀 $code${red}"
        fi
    }

    __mkps1_exitcode() {

        # We need to run a function at runtime to evaluate the exitcode.
        echo "\$(__mkps1_inject_exitcode \$?)"
    }
    
    PROMPT_COMMAND='__git_ps1 "${yellow}\u ${bg_grey}${black} $(__pwd_fancy)${grey}" "$(__mkps1_exitcode) ${reset_bg}${reset} " " ${bg_blue}${bold}${black}${bg_blue}  %s${unbold}${blue}"'

I've been tinkering with this for a while, so the problems that have come up vary. Sometimes, the newline works fine, but when I try to go back to the previous line (ctrl+left arrow), I can't, or I end up deleting the text of the previous prompt, or something weird. I'm sure this is a problem with escaping the color codes, since similar issues are scattered all around this stack exchange. But if I surround the colors in \[...\] the brackets show up in the prompt. I'm not sure where my weak link is, and would really appreciate some help!

New contributor
Smiley Tiger is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • Please edit and provide mcve. For now your code is not complete, it obviously depends on __git_ps1, __pwd_fancy and other things you did not define in the snippet. Shall we take them from the external site you linked to? They are not behind the link and we are not going to search the entire project. Your question should be standalone, please edit and make it so. Commented 2 days ago

1 Answer 1

0

You still need to surround each color code with brackets for the same reason, but instead of \[ and \], they have to be \001 \002.

The latter are what the Readline library actually expects, while \[ \] are just an alias provided by Bash for its PS1 – but it seems that Bash translates them to their Readline equivalents before processing the $() substitutions, not after, so the translation doesn't apply to command output.

The use of \001 \002 also applies to all other programs that use Readline and have customizable prompts (such as the Python REPL).

1
  • Thank you SO much - instantly solved! You are a lifesaver Commented 2 days ago

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .