Getting error: bash: parse_git_branch: command not found

Getting error: bash: parse_git_branch: command not found

我是运行命令:

sudo bash

但我的终端上不断出现错误,提示

bash: parse_git_branch: command not found

这是我的 .bash_profile 文件

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ ()/'
}

export PS1="\u@\h \[3[32m\]\w - $(parse_git_branch)\[3[00m\] $ "

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM$

if [ -f ~/.git-completion.bash ]; then
  . ~/.git-completion.bash
fi

export PATH=/usr/local/bin:/Applications/XAMPP/xamppfiles/bin:$PATH
export PATH=/bin:/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:$PATH
export EDITOR='subl -w'



export JAVA_HOME=$(/usr/libexec/java_home)
export JAVA_HOME=$(/usr/libexec/java_home)
export JAVA_HOME=$(/usr/libexec/java_home)

提前致谢。

通过查看您的 .bash_profile,您似乎忘记在 [=27] 之前添加关键字 function =]() {}

尝试更改为,

function parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ ()/'
}

之后,重新加载您的 。bash_profile 看看它是否有效。

参考:Functions in Bash.

问题是 parse_git_branch.bash_profile 中定义,但没有导出。当您 运行 sudo bash 时,它会启动一个 nonlogin shell 来源 .bashrc 而不是 .bash_profilePS1 已导出,因此在新的 shell 中定义,但 parse_git_branch 不是。

通常,您会在 .bashrc 中同时定义 PS1parse_git_branch,并且两者都不导出。 macOS 与 Linux 略有不同,终端仿真器启动登录 shell 而不是普通的交互 shell。一个好的做法是将定义放在 .bashrc 中,然后从 .bash_profile.

中获取 .bashrc

以下是我将如何拆分您现有的 .bash_profile

.bashrc中:

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ ()/'
}

PS1="\u@\h \[3[32m\]\w - $(parse_git_branch)\[3[00m\] $ "

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM$

if [ -f ~/.git-completion.bash ]; then
  . ~/.git-completion.bash
fi

.bash_profile中:

# Many of the paths you were adding to PATH should already be
# there in the default configuration; run /usr/lib/path_helper
# to see the default.
PATH=/Applications/XAMPP/xamppfiles/bin:/usr/local/sbin:$PATH
export EDITOR='subl -w'
export JAVA_HOME=$(/usr/libexec/java_home)

[[ -f ~/.bashrc ]] && source ~/.bashrc

在我的案例中解决问题的方法是将 hashbang#!/bin/bash - 或者在你的案例中最后可能是 tcsh)添加到我的 .bashrc.

开始

如果 .bashrc 顶部没有 hashbang,该功能仍然适用于 PS1 但仅在主分区内(在我的 SSD 上),但是当我尝试操作 git 存储库时在另一个安装座(一个额外的 HDD)上,我收到了这条消息。

所以只需添加 #!/bin/bash 然后重新加载 .bashrc(通过执行 source ~.bashrc)就可以解决这个问题。