user414441
user414441

Reputation:

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?

Upvotes: 2

Views: 543

Answers (2)

chicks
chicks

Reputation: 2463

To extend Ralf's answer to make the command bold in bash 4.4+ requires setting PS1 and PS0 like so:

PS1="\[\e[32m\]\u@\h \t \W \\$\[\e[0;30;1m\] "
PS0="\[$(tput sgr0)\]"

Obviously you might not like my boring prompt, but it gives you a starting place with the command in bold. The \[\e[0;30;1m\] is setting the command to be displayed in black text and bold. Other color choices may suit you better.

I found this handy when using asciinema to capture examples for documentation. It reminds me of the O'Reilly style of including UNIX console examples with the command in bold.

Upvotes: 1

Ralf
Ralf

Reputation: 1813

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.

Upvotes: 2

Related Questions