解释 csh 中的转义序列?

Interpreting escape sequences in csh?

我有一个小脚本来为当前目录中的 git 存储库的状态着色:

#!/usr/bin/env bash

# setup escape codes based on out output format
RD="\e[0;31m"
GN="\e[0;32m"
LG="\e[0;37m"
BL="\e[0;34m"

# return an evil star if git repo is dirty
git_dirty() {
    ERROR="${RD}✘ "
    git diff-files --no-ext-diff --quiet
    if [[ $? -gt 0 ]]; then
        echo -ne "$ERROR"
        return 0
    fi

    git diff-index --no-ext-diff --quiet --cached HEAD
    if [[ $? -gt 0 ]]; then
        echo -ne "$ERROR"
        return 0
    fi

    echo -ne "${GN}✓ "
}

# format current git branch
BRANCH=$(git symbolic-ref -q HEAD 2> /dev/null | sed -e 's|^refs/heads/||')
if [[ -z "${BRANCH// }" ]]; then
    echo -ne ""
else
    echo -ne "${LG}[${BL}$BRANCH`git_dirty`${LG}]"
fi

当我在 bash 的提示中使用它时效果很好:

export PS1="$LG\n[\!] -${LG}bash${LG}- $LG\u$DG@$RD\h $GN\w $(git_branch)\n$LG └─► $RES"

但是当我在 csh 的提示中使用它时:

set prompt = "${LG}\n\[%!\] -${RD}csh${LG}- ${LG}%n${DG}@${RD}%m ${GN}%~ `git_branch`\n${LG} └─► ${RES}"

它打印 ^[[0;37m[^[[0;34mmaster^[[0;31m✘ ^[[0;37m] 而不是彩色的分支名称和状态。虽然

echo `git_branch` 

按预期工作。如何让 csh/tcsh 正确解释转义序列?

根据 https://www.cs.umd.edu/~srhuang/teaching/code_snippets/prompt_color.tcsh.html 你应该把转义序列放在 %{ } in csh.

set     red="%{3[1;31m%}"
set   green="%{3[0;32m%}"
set  yellow="%{3[1;33m%}"
set    blue="%{3[1;34m%}"
set magenta="%{3[1;35m%}"
set    cyan="%{3[1;36m%}"
set   white="%{3[0;37m%}"
set     end="%{3[0m%}" # This is needed at the end... :(

set prompt = "${white}\n\[%!\] -${red}csh${white}- ${white}%n${DG}@${red}%m ${green}%~ `git_branch`\n${white} └─► ${RES}${end}"

如果想让GIT分支更新,需要把prompt设置放在precmd别名里,在每个命令前求值:

alias precmd 'set prompt = "${white}\n\[%!\] -${red}csh${white}- ${white}%n${DG}@${red}%m ${green}%~ `git_branch`\n${white} └─► ${RES}${end}"'