Search code examples
linuxbashps1

Programming environment?


I'm trying to add color to a part of my Ubuntu bash prompt. This part isn't working: (\e[0;31m\1\e[m) It works, however, if I place it within the PS1 export.

What am I doing wrong?

show_git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\e\[0;31m\1\e\[m) /'
}

export PS1="\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$(show_git_branch)\$ "

Solution

  • Let's imagine you asked this question:

    • Why does putting \e\[0;31m in PS1 variable content result in a colored text output, when putting the same string inside sed s command replacement expression does not result in colored output?

    It's because Bash when printing the content of PS1 variable changes the sequence of two characters \ and e by the byte with the value 033 octal or 0x1b hexadecimal. In contrast, for sed the sequence of \ e characters as part of replacement expression is technically invalid and in practice is not interpreted specially and with GNU sed just results in a literal e character on output.

    If you want to output the hex byte 0x1b with GNU sed you can use the \x1b escape sequence, or you can rely on Bash ANSI-C quoting to pass the byte literally to sed.

    echo a | sed 's/^/\x1b\[31m/'
    # or
    echo a | sed 's/^/'$'\e''\[31m/'
    # the same
    echo a | sed 's/^/'$'\E''\[31m/'