0

I want to display the version of Node in my bash command prompt. I created a function to generate that portion of PS1. It gets the major version of Node, and colors it based on its numeric value. In my .bash_profile:

nv_ps1 () {
  nv_re="v([0-9]+)\.[0-9]+\.[0-9]"
  if [[ $($NVM_BIN/node --version) =~ $nv_re ]]; then
    nv_major=${BASH_REMATCH[1]}
    let nv_color=$nv_major+26
    echo "\[\e[${nv_color}m\]$nv_major\[\e[m\]"
  fi
}

export PS1="[\$(nv_ps1) \[\e[36m\]\t\[\e[m\] \W]\\$ "

The escape sequences in the function output don't get evaluated, though, and the command prompt ends up looking like this:

[\[\e[34m\]8\[\e[m\] 08:54:58 ~]$ 

How can i get this to work?

  • Consider using PROMPT_COMMAND to build the value of PS1 rather than embedding commands in the prompt itself. – chepner Nov 18 '17 at 18:52
-1

In your function nv_ps1, try with echo -e "\033[${nv_color}m${nv_major}\033[0m", it should be better

  • Nope, i still get the same thing... – Brett38 Nov 17 '17 at 17:24
  • exactly the same? in your case I'm pretty sure you have to set the '-e' to evaluate colors : [vm-test-lnx 18:24:38 ~]# echo "[\033[0;31mtest\033[0m]" [\033[0;31mtest\033[0m] [vm-test-lnx 18:24:41 ~]# echo -e "[\033[0;31mtest\033[0m]" [test] I'm doing some tests and I'll come back – R.Dussin Nov 17 '17 at 17:26
  • Try with : echo -e "\033[${nv_color}m${nv_major}\033[0m" Please also verify the output of your term by doing "echo $TERM" – R.Dussin Nov 17 '17 at 17:33
1

The shell evaluate escaped chars before running the command nv_ps1. So this command should not output escaped chars, they will just be displayed verbatim. Ascii codes (colors) can be outputted by nv_ps1 if you convert them before, that's why echo -e seems to be enough. But \[ and \] are specific to PS1 interpretation, you have no way to output them from your function. You can ignore this, but you may be disappointed sooner or later.

The simplest solution is export PS1="[$(nv_ps1) \[\e[36m\]\t\[\e[m\] \W]\\$ ". Thus, escaped chars are stored directly in PS1 on assignment.
Advantage : Only evaluate nv_ps1 once, so the shell do not fork on every prompt.
Drawback : Only evaluate nv_ps1 once, so if Node is updated, currently open shells prompt would not (but you can source ~/.bashrc).

If you really want to keep the prompt up to date, you must have two functions calls export PS1="[\[\$(nv_ps1 color)\]\$(nv_ps1 version)\[\e[m\] \[\e[36m\]\t\[\e[m\] \W]\\$ ", and put this in your function [[ $1 == color ]] && printf "\e[${nv_color}m" || printf "${nv_major}".

Side notes :

  • Exporting PS1 is not necessary.
  • Using local variables is preferred :

    local nv_re="v([0-9]+)\.[0-9]+\.[0-9]"
    local nv_major="${BASH_REMATCH[1]}"
    local nv_color=$((nv_major + 26))
    

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.