Search code examples
bashprompt

bash prompt: highlight command being entered


Entering a command on bash goes like this:

<Prompt $>  <The Command I Entered>
<Output Of The Command>

I'm looking a way to make The Command I Entered bold. It's easy to start bold from prompt with putting tput bold in PS1.

However the questions is, how to tput sgr0 it when Enter is pressed. Can i use readline / bash magic to achieve this?


Solution

  • Pre Bash 4.4:

    In bash 4.3.x (and maybe earlier), the "debug trap" is executed before a command from the command line is executed.

    trap 'tput sgr0' DEBUG
    

    But this has one disadvantage: It is executed before every simple command that is executed. So if you run:

    $ echo Hello && echo World 
    

    The debug trap is called two times.

    Then the following command will not work as expected:

    tput setaf 1 ; echo "This is red"
    

    The printed "This is red" will not be red.

    See DEBUG trap and PROMPT_COMMAND in Bash and also the accepted answer to this question.

    Bash 4.4

    In Bash 4.4 the variable $PS0 was introduced. Here is a quote from the man page:

    The value of this parameter is expanded (see PROMPTING below) and displayed by interactive shells after reading a command and before the command is executed.

    So with bash 4.4 you could do the following:

    PS0="\[$(tput sgr0)\]"
    

    The \[\] are used to enclose unprintable characters (here the terminal control sequence to reset text attributes). I'm not sure if this is really needed for PS0, but it can't hurt. There is no visual difference in the shell output either way.