【问题标题】:Bash: check if the current directory is a Git RepositoryBash:检查当前目录是否为 Git 存储库
【发布时间】:2020-11-05 11:48:50
【问题描述】:

我的XFCE terminal 有一个颜色模式,当我位于Git Repository 的目录中时,我尝试设置分支名称和颜色。

其实这是我bash的配置:

PS1="\u@\h $(if [[ ${EUID} == 0 ]]; then echo '\W'; else echo '\w'; fi) \$([[ \$? != 0 ]] && echo \":( \")\$ "

当我在一个 Git 存储库的目录中时,我想表明:

[\u@\h \W]\[\033[00;32m\]\$(git_branch)\[\033[00m\]\$

这是git_branch function:

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

我尝试将PS1 编辑为:

\$(if [[git rev-parse --is-inside-work-tree]]; then [\u@\h \W]\[\033[00;32m\]\$(git_branch)\[\033[00m\]\$

但它不起作用 - 当我在 Git 存储库的目录中时,它不会显示分支的名称。

非常感谢!

【问题讨论】:

  • “它不起作用”是什么意思?
  • 当我在 git 目录中时,它不会显示分支的名称。
  • if [[...]]; then [\u@\h \W] 将尝试运行名为 [\u@\h 的命令。
  • 另外:在你的 git 安装的 contrib/ 文件中查找 __git_ps1 函数,在 contrib/completion/git-completion.bash 或 contrib/completion/git-prompt.sh 中

标签: linux bash git terminal xfce


【解决方案1】:

要检查目录是否在git控制下,可以source以下sn-p:

# mygitprompt.sh
PROMPT_COMMAND="CheckIfGitDir"

CheckIfGitDir()
{
    if git status &>/dev/null; then
        echo "Directory is under the control of git"
    else
        echo "There is no sign of git anywhere"
    fi
}

如何获取:

source /path/to/mygitprompt.sh

每次按回车,PROMPT_COMMAND 中的命令都会被执行。

【讨论】:

    猜你喜欢
    • 2011-01-11
    • 2016-04-03
    • 2017-01-23
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 2020-02-05
    • 2020-08-09
    • 2015-10-21
    相关资源
    最近更新 更多