0

I want my terminal prompt to change color depending on success of the previous command. Currently I achieve this with the following script:

exitstatus()
{
    if [[ $? == 0 ]]; then
        echo -e "\e[38;5;45mबरें"
    else
        echo -e "\e[38;5;211mचूक"
    fi
}
PS1="\[\e[38;5;252m\][\[\e[38;5;214m\]\A \$(exitstatus)\[\e[38;5;252m\]]> \[\e[0m\]"

Problem here is that echo inside exitstatus doesn't escape colors correctly, leaving some invisible characters. That causes my terminal to cut line short and write the new one on top of the previous when I type long commands. enter image description here

With PS1 variable I solved this issue by adding \[\] around \e[...m. Echo, however, doesn't have square brackets as escape characters and I can't find a way to make it escape colors correctly.

6
  • 1
    Can you show us how this fails? I just tried your code on my machine and it seems to be working as expected. You probably want to use printf instead of echo, but that is always true and not specific to your issue. See Why is printf better than echo?. Commented Nov 17, 2022 at 15:24
  • @terdon added an illustration. Commented Nov 17, 2022 at 15:54
  • I can't reproduce this. What happens if you try with a new user? Commented Nov 17, 2022 at 15:55
  • @terdon Same. printf doesn't seem to help either. Commented Nov 17, 2022 at 16:03
  • Better use liquidprompt Commented Nov 17, 2022 at 16:43

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.