P i
P i

Reputation: 30784

Tidy up `\[ ... \]` in bash

I'm pimping my bash prompt.

PS1="\n\[${DIM}\][\u@\h] \[${BLUE}\]\w \[${YELLOW}\]\$(git_branch)\n\[${BRIGHT}\]> "

^ This gets rather hard to read.

Is there any way of cleaning it up?

Something like:

ESC() {
  printf '\001%s\002' "$1"
}

?

Full (working) code is here (needs a dark background):

function rgb {
    # https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit
    let "sum = 16 + 36*$1 + 6*$2 + $3"
    tput setaf ${sum}
}

# https://coderwall.com/p/fasnya/add-git-branch-name-to-bash-prompt
git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

  BOLD=$(tput bold)
 RESET=$(tput sgr0)
   DIM=$(tput dim)


BRIGHT=$(rgb 5 5 5)
  BLUE=$(rgb 1 1 5)
YELLOW=$(rgb 4 4 1)

PS1="\n\[${DIM}\][\u@\h] \[${BLUE}\]\w \[${YELLOW}\]\$(git_branch)\n\[${BRIGHT}\]> "
PS2="\[${BOLD}\]>\[${RESET}\] "

trap 'echo -ne "${RESET}" > $(tty)' DEBUG

Upvotes: 0

Views: 42

Answers (1)

chepner
chepner

Reputation: 532508

You don't have to define PS1 in one shot. Add one chunk at a time, and comment the line(s) whose meaning you expect you'll forget

PS1="\n\[$DIM\]"
PS1+="\u@\h "   # `bash` already knows how to compute the length of its own
                # escape sequences, and using \[...\] here would cause bash to
                # *under*estimate, rather than *over*estimate, the prompt length.
PS1+="\[${BLUE}\]\w "
# etc

Upvotes: 2

Related Questions