用bash整理`\ [... \]`

时间:2018-06-14 17:36:16

标签: bash escaping

我正在拉扯我的bash提示。

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

^这很难读懂。

有没有办法清理它?

类似的东西:

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

完整(工作)代码在这里(需要深色背景):

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

1 个答案:

答案 0 :(得分:2)

您不必一次定义PS1。一次添加一个块,并评论您希望忘记其意义的行

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