__git_ps1 未找到但确实存在

jan*_*anw 4 command-line bash prompt ps1

~/.bash_aliases我设置 PS1 的地方,并包含在~/.bashrc(默认设置)中

# color PS1
PS1="\[\033[01;90m\]\D{%H:%M} \[\033[01;33m\]Ubuntu\[\033[00m\] \[\033[01;34m\]\w\[\033[01;35m\]$(__git_ps1) \[\033[01;36m\]\$\[\033[00m\] "
Run Code Online (Sandbox Code Playgroud)

但是当我启动终端时出现错误__git_ps1: command not found

但是当我$ __git_ps1在 git 文件夹中运行函数手册时,它会回显当前分支。

另外当我手动运行时
$ PS1="\[\033[01;90m\]\D{%H:%M} \[\033[01;33m\]Ubuntu\[\033[00m\] \[\033[01;34m\]\w\[\033[01;35m\]$(__git_ps1) \[\033[01;36m\]\$\[\033[00m\] "

PS1 得到更新,__git_ps1部分确实得到了添加。

我自己没有安装。我只安装了git。
sudo apt install -y git (git 版本 2.19.1)

__git_ps1/usr/lib/git-core/git-sh-promptgithub上的文件)中定义

grep __git_ps1 ~/.bashrc ~/.profile ~/.bash_profile ~/bash.login ~/.bash_aliases /etc/bash.bashrc /etc/profile /etc/profile.d/* /etc/environment 2>/dev/null
Run Code Online (Sandbox Code Playgroud)

只显示.bash_aliases文件。
git-sh-promt 的完整 grep 只返回二进制匹配

sudo grep 'git-sh-prompt' -nr /
Run Code Online (Sandbox Code Playgroud)

这里有什么问题?

PS1怪异

wja*_*rea 5

为了清晰起见,使用去色版本:

PS1="\D{%H:%M} Ubuntu \w$(__git_ps1) \$ "
Run Code Online (Sandbox Code Playgroud)

双引号告诉 Bash 评估引号之间的内容,包括$(__git_ps1),但/usr/lib/git-core/git-sh-prompt还没有被引用,因此是错误的。

只需将其更改为使用单引号,这将阻止$(__git_ps1)在评估 PS1 之前进行评估(即当交互式 shell 准备好输入并显示提示时)。

PS1='\D{%H:%M} Ubuntu \w$(__git_ps1) \$ '
Run Code Online (Sandbox Code Playgroud)

转义美元符号也有效,但更难阅读:

PS1="\D{%H:%M} Ubuntu \w\$(__git_ps1) \$ "
Run Code Online (Sandbox Code Playgroud)

顺便说一下,~/.bash_aliases它是用于 shell 别名的,所以把你的PS1. 就我个人而言,我会把它放进去~/.bashrc