Reputation: 197
I am trying to create a colourful and somewhat informative bash prompt but I cannot figure out how to save the $? exit code for later use after the if test (which seems to change $?). Doing:
exit_code=$?
PS1="\$(if (( \$? == 0 )); then echo \"$GREEN\"; else echo \"$RED\"; fi)$exit_code $NORMAL\u@\h $BLUE\W`if (( $UID == 0 )); then echo \"$RED#\" else echo \"$GREEN$\"; fi`$NORMAL "
does not seem to work either. Both $? and exit_code will be 0 after the test.
I am sure this is possible somehow in bash, but how?
This is my PS1 so far:
PS1="\$(if (( \$? == 0 )); then echo \"$GREEN\"; else echo \"$RED\"; fi)$?$NORMAL\u@\h $BLUE\W`if (( $UID == 0 )); then echo \"$RED#\" else echo \"$GREEN$\"; fi`$NORMAL "
And $? is just zero even though the colour changes between red and green depending on the exit code, this is what makes me thing that it is the if test that sets it to zero.
I know it would be easier to read if split up on multiple lines but I prefer to keep this as a one liner.
If you see any other errors please also let me know as I am just poking here and there to see what works because I am getting quite confused about where I need to put backslashes and where I don't.
GREEN, BLUE, RED and NORMAL are just colours defined above to make things less cryptic.
Upvotes: 0
Views: 654
Reputation: 246774
I build my prompt this way:
user_host_path="${debian_chroot:+($debian_chroot) }"'\u@\h: \w'
xterm_title='\[\e]0;'"$user_host_path"'\a\]'
[[ $TERM == xterm* || $TERM == rxvt* ]] && line1="${xterm_title}"
git_branch='$(git_current_branch)'
line1="${line1}${user_host_path}${git_branch}"
line2='\! \$ '
print_time='printf "%*s" $((COLUMNS - 9)) " "|sed "s/./˙/g"; date "+ %T"'
color_bold='\[\033[0;1m\]'
color_reset='\[\033[0m\]'
PROMPT_COMMAND="_rc_=\$?;${print_time};((_rc_!=0)) && PS1='${line1}\n${color_bold}[\$_rc_]${color_reset} ${line2}' || PS1='${line1}\n${line2}'"
So, the key is to save $?
inside the prompt var.
Upvotes: 1