Bash Prompt with Last Exit Code

后端 未结 7 1737
余生分开走
余生分开走 2020-11-30 22:12

So, I\'ve been trying to customize by bash prompt so that it will look like

[feralin@localhost ~]$ _

with colors. I managed to get constant

7条回答
  •  温柔的废话
    2020-11-30 22:48

    If you don't want to use the prompt command there's two things you need to take into account:

    1. getting the value of $? before anything else, otherwise it'll be overriden
    2. escaping all the $'s in the PS1 (so it's not evaluated when you assign it)

    Working example using a variable

    PS1="\$(VALU="\$?" ; echo \$VALU ; date ; if [ \$VALU == 0 ]; then echo zero; else echo nonzero; fi) " 
    

    Working example without a variable

    Here the if needs to be the first thing, before any command that would override the $?.

    PS1="\$(if [ \$? == 0 ]; then echo zero; else echo nonzero; fi) "
    

    Notice how the \$() is escaped so it's not executed right away but each time PS1 is used. Also all the uses of \$?

提交回复
热议问题