twolfson / sexy-bash-prompt

Bash prompt with colors, git statuses, and git branches.
MIT License
1.14k stars 154 forks source link

Exit status changed #52

Closed techhazard closed 9 years ago

techhazard commented 9 years ago

I wanted to add the exit status to the prompt, but it always returns zero, even when it shouldn't. I tested it with rm x which returns 1 since x doesn't exist.

twolfson commented 9 years ago

Can you elaborate on when it's returning zero? The prompt does not affect bash internals:

underdog at Euclid in ~
$ rm x
rm: cannot remove ‘x’: No such file or directory
underdog at Euclid in ~
$ echo $?
1
techhazard commented 9 years ago

I have a very simple function to display the exit function.

function get_exit_status() {
   es="$?"
   if [ $es -ne 0 ]
    then
       echo -ne "\n exit code: $es"
    fi
} 

and this now works if I put it before the git section in the prompt, but after the git section it always returns error 128 when not in a git repo and 0 otherwise

twolfson commented 9 years ago

Oooh, I understand what is happening now. You are cloning our prompt and modifying it.

From the initial phrasing, it sounded like you were getting bad exit codes when using bash normally.

In your case, you will need to grab the exit code before any of our commands are executed. bash will only save it for the last command run.

This should be possible via @rpdelaney's work that places sexy_bash_prompt as a command as I cannot think of a way to make it work in the one-liner fashion.

https://github.com/rpdelaney/sexy-bash-prompt/blob/690985b7211d173510eb324ff175c3370a7b0e0b/sexy-bash-prompt#L235-L265

sexy_bash_prompt () {
  # Save exit code
  exit_code="$?"

  # Run normal prompt actions
  printf ...

  # Whenever you want to update the prompt with your exit code customization
  if [[ "$exit_code" -ne 0 ]]; then
    echo "Bad exit code"
  fi
}
twolfson commented 9 years ago

For reference, that commit is from this issue: https://github.com/twolfson/sexy-bash-prompt/issues/36

rpdelaney commented 9 years ago

Since sexy-bash-prompt works by initializing the PS1, not via a function, this isn't directly possible. But it can be done by prepending the PS1 with a function to grab the exit status, as shown here: 58173f4

techhazard commented 9 years ago

Well, I now use my exit status in front of the sexy git, and I'm fine with that.
Here is a screenshot

twolfson commented 9 years ago

Cool, closing this issue then. Glad everything worked out =)

techhazard commented 9 years ago

It did still bother me a little, and I recently found out that there is a variable called PROMPT_COMMAND that contains a list of function names to be executed before the PS1 is printed. I used that to capture the exit status, and now I have this: Imgur
the lines of git status, background jobs, CPU usage and exit code (plus empty line) are shown when needed (e.g. CPU > 24%)