My goal is to have a bash prompt that displays a shortened username, a shortened path in blue, and a counter variable that gets reset every time I mistype a command (which I will check with $?, though this is not strictly the same).

Right now, my ~/.bashrc has:

#should increment counter if no errors, else reset counter
PROMPT_COMMAND="if [ $? -eq 0 ]; then ((counter++)); else counter=0; fi"
PS1='(${USER:0:3}@\[\e[0;34m\]$(basename $(dirname $PWD))/$(basename $PWD)\[\e[m\])[$counter]\\$ '

This displays:


My main problem is that counter is never reset to zero when I get a nonzero exit status. I can run the command in PROMPT_COMMAND after a failed command such as aasdjfasdf and echo $counter will show a 0 (actually, a 1, since PROMPT_COMMAND increments it immediately).

My other lesser problem is that in the root directory my prompt will display


which is less than ideal (the 3 /'s). I'm not sure how to fix that either, but at least it's not as big of a deal.

How do I get PROMPT_COMMAND to correctly increment and reset counter?

edit: Here is my PS1 that does everything I want, in case others are curious:

PROMPT_COMMAND='if [ $? -eq 0 ]; then ((counter++)); else counter=0; fi;'
PS1='(\[\e[4m\]${USER:0:3}\[\e[0m\]@\[\e[34m\]${PWD:${#PWD}<15?0:(-15)}\[\e[m\])[$counter]\\$ '
  • @Sinjai, you are wrong. Have you tried this? May 11 at 19:16
  • I am wrong – I tested it, but poorly. Classic single vs double quotes issue. If you define PS1 properly as you've shown above, $counter will remain in the string verbatim and be re-expanded each time $PS1 is used by the shell, as intended. I'm going to delete my comment to avoid wasting future visitors' time (and out of shame).
    – Sinjai
    May 11 at 22:37

1 Answer 1


Change PROMPT_COMMAND to be:

PROMPT_COMMAND='if [ $? -eq 0 ]; then counter=$((counter+1)); else counter=0; fi'

Use single-quotes to prevent premature expansion of $?, and use direct assignment for the incremented value of counter.

  • 1
    This would increment the counter even if you just press Enter.
    – Kusalananda
    Mar 30, 2018 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.