1

How do I capture the exit value of the previous command in my bash prompt? I want to do this because I also want to include the current git branch in my path as well, and that changes $?

I have tried quite a few variations on the following prompt (e.g. `, ` and $() around the assignment to RETVAL), but RETVAL is empty in all of them:

PS1="\$(RETVAL=$(echo \$))\$(cd 124123)retval: $RETVAL"

The cd command inside is just a placeholder for the call to the git current branch function, and I am echoing RETVAL afterwards (this is always an empty string to test if it gets assigned.

Other questions that are similar/relevant:

I have also tried setting RETVAL in the prompt command using examples like on these pages, but nothing is displayed in the prompt

Community
  • 1
  • 1
cfogelberg
  • 1,468
  • 19
  • 26

2 Answers2

4

Make a function that generates your prompt, and save $?:

makeprompt() { 
    status=$?
    echo "$(echo someoutput) $status"
    return $status
}

PS1='$(makeprompt) \$ '

This will give you both the output of the command (here echo, but could be git), and the exit status of the previously executed command.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • Thanks for suggesting this response - I think it's got me most of the way there. The problem now is that the bash path is not being properly parsed. E.g. I have: `makeprompt() { echo = "\n$ " }` (with correct whitespacing in code) but it sets my prompt literally to the string "\n $" and does not put an empty new line before it. Of course my actual prompt is more complex than this with color codes and the git branch parse function, but it does not fit in this comment box. It fails in the same way though. Edit: Pushed return rather than shift-return and posted the comment early – cfogelberg Aug 13 '13 at 21:28
  • 1
    Special PS1 variables (like `\$` in this example), have to be specified literally and can't be echoed in makeprompt. For line feeds, you can use `echo -e '\n\n\n foo'`. Keep in mind that makeprompt can't output trailing line feeds, as `$(..)` strips them. – that other guy Aug 13 '13 at 21:34
  • I was using a lot of those in my prompt (\u, \h, \D etc) but I was able to replace them all with variables so I'm all sorted now. Thanks for all your help :) – cfogelberg Aug 15 '13 at 23:14
1

From bash(1)

PROMPT_COMMAND
  If set, the value is executed as a command  
  prior  to  issuing  each  primary prompt.

Use this, instead of PS1. Your assignment of PS1 is expanded once, on assigment, but NOT every time the prompt is displayed. Yes, when it is dipslayed, some expansion is done, but it is mor limited (and uses -style substitution "variables" - again, see bash(1)).

M.E.L.
  • 613
  • 3
  • 8