0

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:

counter=0
#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:

(use@//home)[17]$

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

(use@///)[11]$

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:

counter=0
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]\\$ '
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.

  • This would inclement the counter even if you just press Enter. – Kusalananda Mar 30 '18 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.