Getting a dynamic bash PS1 prompt to the right

I am working on a dynamic bash prompt where I want to tell in PS1 which version of the configuration file is included in the local file system. This is a far-fetched example of what I'm trying to do, simplified. What goes wrong: bad wraps and / or brackets appear. Can anyone determine what I am doing wrong?

If the far-fetched configuration matches "v2", I want to see this version in PS1 as YELLOW. If it is "v1", GREEN will appear in the line. Setup:

$ grep FOOVER foo-*.conf foo-v1.conf:# FOOVER xyz-v1 foo-v2.conf:# FOOVER zet-v2 

I would then symlink foo.conf foo-v1.conf. My bashrc:

  0 GREEN=$(tput setaf 034) 1 YELLOW=$(tput setaf 3) 2 BLUE=$(tput setaf 4) 3 CYAN=$(tput setaf 6) 4 BOLD=$(tput bold) 5 RESET=$(tput sgr0) 6 CONF=$HOME/foo.conf 7 8 function __get_foo_version () { 9 FOOVER=$(grep FOOVER $CONF | awk '{print $3}') 10 if [[ "$FOOVER" =~ v2$ ]]; then 11 style_foover="${BOLD}${YELLOW}$FOOVER" 12 #style_foover="\[${BOLD}${YELLOW}\]$FOOVER" 13 elif [[ "$FOOVER" =~ v1$ ]]; then 14 style_foover="${BOLD}${GREEN}$FOOVER" 15 #style_foover="\[${BOLD}${GREEN}\]$FOOVER" 16 fi 17 echo $style_foover 18 } 19 20 style_host="\[${RESET}${BLUE}\]" 21 style_path="\[${RESET}${CYAN}\]" 22 style_reset="\[${RESET}\]" 23 24 PS1=' user@ ' 25 PS1+="${style_host}host" 26 PS1+="${style_reset} " 27 PS1+="\$(__get_foo_version) " 28 PS1+="${style_reset}" 29 PS1+="${style_path}\W" 30 PS1+="${style_reset} $ " 

When I run the above, I get this behavior that looks good at first: http://imgur.com/HIR3SoA

But when I arrow up to a long team, bad packaging happens: http://imgur.com/qLfdUor

When I turn off lines 11, 14 and turn on lines 12, 15, I get brackets designed to handle non-printable characters displayed on PS1:

(not enough reputation points to place more than two links :( imgur.com slash nkXFDyJ)

 user@host \[\]xyz-v1 ~ $ 

..and I still get poor packaging in this case.

+4
source share
1 answer

Use \ x01 (or \ 001) and \ x02 (or \ 002) and then evaluate them with echo -e:

  function __get_foo_version () { FOOVER=$(grep FOOVER $CONF | awk '{print $3}') if [[ "$FOOVER" =~ v2$ ]]; then #style_foover="${BOLD}${YELLOW}$FOOVER" >>> style_foover="\x01${BOLD}${YELLOW}\x02$FOOVER" elif [[ "$FOOVER" =~ v1$ ]]; then #style_foover="${BOLD}${GREEN}$FOOVER" >>> style_foover="\x01${BOLD}${GREEN}\x02$FOOVER" fi >>> echo -e "$style_foover" } 

A more complete answer about why this fix is ​​here: https://superuser.com/questions/301353/escape-non-printing-characters-in-a-function-for-a-bash-prompt

+5
source

Source: https://habr.com/ru/post/972494/


All Articles