Bash Prompt with Last Exit Code

后端 未结 7 1714
余生分开走
余生分开走 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 23:07

    Compact solution:

    PS1='... $(code=${?##0};echo ${code:+[error: ${code}]})'
    

    This approach does not require PROMPT_COMMAND (apparently this can be slower sometimes) and prints [error: <code>] if the exit code is non-zero, and nothing if it's zero:

    ... > false
    ... [error: 1]> true
    ... >
    

    Change the [error: ${code}] part depending on your liking, with ${code} being the non-zero code to print.

    Note the use of ' to ensure the inline $() shell gets executed when PS1 is evaluated later, not when the shell is started.

    As bonus, you can make it colorful in red by adding \e[01;31m in front and \e[00m after to reset:

    PS1='... \e[01;31m$(code=${?##0};echo ${code:+[error: ${code}]})\e[00m'
    

    --

    How it works:

    • it uses bash parameter substitution
    • first, the ${?##0} will read the exit code $? of the previous command
    • the ## will remove any 0 pattern from the beginning, effectively making a 0 result an empty var (thanks @blaskovicz for the trick)
    • we assign this to a temporary code variable as we need to do another substitution, and they can't be nested
    • the ${code:+REPLACEMENT} will print the REPLACEMENT part only if the variable code is set (non-empty)
    • this way we can add some text and brackets around it, and reference the variable again inline: [error: ${code}]
    0 讨论(0)
提交回复
热议问题