Reputation: 1383
get_git_branch(){
local branch__=
git branch &> /dev/null
if [ $? -eq 0 ]; then
branch__=`git branch --no-color | sed -ne 's/^\* \(.*\)$/\1/1p' | tr a-z A-Z`
else
branch__="NORMAL"
fi
echo -n $branch__
}
exit_status(){
local smile__=
if [ $? -eq 0 ]; then
smile__='(*´▽`*)'
else
smile__='(╥﹏╥)'
fi
echo -n $smile__
}
export PS1='[\w]\d\t\$\n\u->(`get_git_branch`)`exit_status`:'
This is PS1 setting in my bashrc,I want to check git branch and exit status in my terminal, get_git_branch works every time PS1 refreshed, but exit_status not, whey exit_status not executed?
Upvotes: 0
Views: 349
Reputation: 295316
It absolutely is executed. However, $?
is changed by other code that's run before it -- like get_git_branch
.
The best practice here is not to embed code where you want detailed flow control in PS1, but rather to use PROMPT_COMMAND
.
get_git_branch(){
local branch
if branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null); then
printf '%s\n' "${branch^^}" # if on bash 3.2, you may need to use tr instead
else
echo "NORMAL"
fi
}
exit_status(){
if (( ${1:-$?} == 0 )); then
printf '%s' '(*´▽`*)'
else
printf '%s' '(╥﹏╥)'
fi
}
build_prompt() {
last_exit_status_=$?
PS1='[\w]\d\t\$\n\u->($(get_git_branch))$(exit_status "$last_exit_status_"):'
}
PROMPT_COMMAND=build_prompt
Upvotes: 2