错误 PS1 git 函数 - Gitbash 与 Cygwin 之间的冲突

问题描述 投票:0回答:1

我在尝试为 git 自定义 PS1 时收到以下错误

错误:

bash: command substitution: line 1: syntax error near unexpected token `)'
bash: command substitution: line 1: `get_dir)'
bash: command substitution: line 1: syntax error near unexpected token `)'
bash: command substitution: line 1: `get_branch)'
bash: command substitution: line 1: syntax error near unexpected token `)'
bash: command substitution: line 1: `parse_git_dirty)'

我的.bashrc

#...
function get_dir() {
    [[ ${PWD} == $HOME ]] && echo '~' || echo ${PWD##*/}
}
function get_branch() {
    [[ -d .git ]] && echo "$(git branch --show-current)" 
}
#...

这很棘手!第一个片段在我的 Cygwin 上完美运行,但在 Gitbash 上产生该错误

export PS1="${LIGHTGREEN}\t${NC} ${PINK}\$(get_dir)${NC}${LIGHTBLUE} \$(get_branch) ${NC}${RED}\$(parse_git_dirty)${NC} \n${GREEN}$ ${NC}"

当我使用此语法“修复它”时,我没有错误,但它不能动态工作。每次更改目录时,我都需要重新加载 .bashrc

export PS1="${LIGHTGREEN}\t${NC} ${PINK}`get_dir`${NC}${LIGHTBLUE} `get_branch` ${NC}${RED}`parse_git_dirty`${NC} \n${GREEN}$ ${NC}"

即更改为

\$(get_dir)
get_dir

Cygwin 上的结果:

bash cygwin git-bash ps1
1个回答
0
投票

在尝试“修复”它时,您会在

get_dir
执行
时执行 export PS1

相反,您需要在每次生成新提示时重新评估它。也许最简单的方法是定义一个函数

my_prompt
,在调用时计算 PS1 字符串,然后设置

export PS1='$(my_prompt)'

这还允许您在提示中激活函数之前调试函数。

© www.soinside.com 2019 - 2024. All rights reserved.