dylnmc
dylnmc

Reputation: 4010

PS1 can't have two "\$"?

I want my bash Prompt String 1 to have both the date/time and the return code of the last command. So, I thought I could just do

PS1="\[\e[00;34;01m\]\$(date +'%a %b %e, %T')\[\e[35m\] \$?\[\e[00m\] >> "

Which I thought would give me a blue date (like Thu Jul 2, 01:01:01) a purple return code and then just >> (given that the ansi escape sequences produce "normal" colors based on most pallets for terminals). However, it doesn't work.


PS1="\$? >> "

and

PS1="\$(date +\"%a %b %e, %T\") >> "

both work, though, and when I do it the first way, only the first "\$" gets interpreted and the other only gets interpreted when my bashrc is sourced. (So, the "\$?" gets evaluated to 0 initially and stays 0.)

Any thoughts as to why this is happening?

Note: I have even tried PS1='$(date +"%a %b %e, %T") $? >> '

Can anyone else replicate this in Unix bash? If so/if not, please leave a comment.

Upvotes: 1

Views: 95

Answers (3)

Brian Campbell
Brian Campbell

Reputation: 332776

It isn't ignoring the $? (\$? is just an escaped version of $? so it isn't evaluated when you set the variable, but rather when the prompt string is expanded).

Instead, it's returning the exit code of the last command you ran; which in this case, is always the $(date ...) command from earlier in the prompt. Since that date command never fails, the return code is always 0.

To work around this, as Ian points out, you can use \D{%a %b %e, %T} instead of \$(date ...) in your prompt string to format the date; since that's built in and not a separate command, it won't clobber $?.

Upvotes: 3

anishsane
anishsane

Reputation: 20980

The $? that you see in the prompt is the exit code of date command. You can verify it as this:

$ PS1="\[\e[00;34;01m\]\$(exit 10)\[\e[35m\] \$?\[\e[00m\] >> "
10 >>

Work-around:

$ PROMPT_COMMAND='EXIT_CODE=$?'
$ PS1="\[\e[00;34;01m\]\$(date +'%a %b %e, %T')\[\e[35m\] \$EXIT_CODE\[\e[00m\] >> "

Upvotes: 1

Ian Petts
Ian Petts

Reputation: 1350

I don't know why bash ignores the second \$, but try using the \D format for the date:

PS1="\[\e[00;34;01m\]\D{%a %b %e, %T}\[\e[35m\] \$?\[\e[00m\] >> "

This works for me under bash version 4.2.46

Upvotes: 1

Related Questions