17

How can I use these red and green arrow signs in the bash prompt?

enter image description here

update 1

This is my .bashrc file

if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\[\033[00m\]\ 
[\033[01;34m\]→  \w\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}→  \w\$ '
fi
unset color_prompt force_color_prompt

I want this arrow to be colored as @dessert answered before (turn red and green for false and true command )

0

2 Answers 2

26

You can use bash’s PROMPT_COMMAND to run a function which builds your prompt, e.g.:

PROMPT_COMMAND=build_prompt

build_prompt() {
  EXIT=$?               # save exit code of last command
  red='\[\e[0;31m\]'    # colors
  green='\[\e[0;32m\]'
  cyan='\[\e[1;36m\]'
  reset='\[\e[0m\]'
  PS1='${debian_chroot:+($debian_chroot)}'  # begin prompt

  if [ $EXIT != 0 ]; then  # add arrow color dependent on exit code
    PS1+="$red"
  else
    PS1+="$green"
  fi

  PS1+="→$reset  $cyan\w$reset \\$ " # construct rest of prompt
}

Add this code to your ~/.bashrc file and open a new terminal or run . ~/.bashrc in an existing one for the changes to take effect. Note that I added the usual \$ at the end, this prints $ normally and # if you’re root, thus preventing you from running commands as root unwittingly. The false command is a good way to test the non-zero exit code variant:

result

If you’re into prompt themeing you should definitely take a look at the zsh shell (package zsh), whose famous configuration framework Oh My Zsh alone comes with over hundred themes. Additionally there are many other plugins available, for example the Spaceship ZSH prompt.

Links

1
  • 1
    While this is a great plain-bash solution, you could take a look at zsh (as a replacement of bash) and especially the Spaceship prompt Mar 27, 2019 at 7:27
0

If someone wants that a virtualenv prompt shows up before the arrows do:

build_prompt() {
    EXIT=$?               
    red='\[\e[1;31m\]'
    green='\[\e[1;32m\]'
    blue='\[\e[1;34m\]'
    cyan='\[\e[1;36m\]'
    reset='\[\e[0m\]'

    PS1='${debian_chroot:+($debian_chroot)}'

    if [ -z "$VIRTUAL_ENV_DISABLE_PROMPT" ] ; then
        _OLD_VIRTUAL_PS1="$PS1"
        if [ "`basename \"$VIRTUAL_ENV\"`" = "__" ] ; then
            PS1="[`basename \`dirname \"$VIRTUAL_ENV\"\``] $PS1"
        elif [ "$VIRTUAL_ENV" != "" ]; then
            PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1"
        fi
        if [ $EXIT != 0 ]; then
            PS1+="$red"
        else
            PS1+="$green"
        fi
    fi
    PS1+="→$reset  $cyan\w$reset \\$ "
    export PS1
}

PROMPT_COMMAND=build_prompt

This is a mix o this current post and this: Why is virtualenv not setting my terminal prompt?

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.