为什么在我的 PS1 末尾添加 \n 会导致替换错误?

Why does adding \n at the end of my PS1 lead to substitution errors?

所以,我在 Windows 上玩我的 PS1 Git bash。

我的 PS1 看起来像这样:

PS1="\n\[3[01;35m\]\u@\h\[3[01;34m\] $PWD \[3[00m\]\[3[01;32m\]$(__git_ps1 "(%s)")\[3[00m\]\nλ "

然后我发现在更改分支时分支名称没有更新,并且发现this answer,这告诉我将双引号替换为单引号。

现在,我的 PS1 看起来像这样:

PS1='\n\[3[01;35m\]\u@\h\[3[01;34m\] $PWD \[3[00m\]\[3[01;32m\]$(__git_ps1 "(%s)")\[3[00m\]\nλ '

突然,我在执行 .bashrc:

时收到警告
bash: command substitution: line 1: syntax error near unexpected token `)'
bash: command substitution: line 1: `__git_ps1 "(%s)")'

进一步调查显示,当我删除 PS1 定义末尾 λ 之前的 \n 时,警告消失。

谁能回答我:


编辑

当我将 $(__git_ps1 "(%s)") 更改为 `__git_ps1 "(%s)"` 时,警告消失,一切正常...

解决方案

NEWLINE="
"
PS1='\[3[01;35m\]\u@\h \[3[01;34m\]$PWD\[3[01;32m\]$(__git_ps1)\[3[00m\]$NEWLINEλ '

换行存在问题,重置颜色也会使行比必要的长。

问题的最小样本:

PS1='$(date)\n$'

看起来像是变量替换的问题。