简体   繁体   中英

Bash: check if the current directory is a Git Repository

I have a color schema for my XFCE terminal and I try to set the branch name and color when I'm inside a directory which is a Git Repository .

Actually this is the configuration of my bash:

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

and when I'm inside a directory which is a Git Repository I want to show that:

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

this is the git_branch function :

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

I tried to edit the PS1 as that:

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

but it isn't working - when I'm inside the directory of Git repository, it doesn't show me the name of the branch.

Thank you very much!

To check if the directory is under git control, you can source the following snippet:

# 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
}

How to source:

source /path/to/mygitprompt.sh

Everytime you hit ENTER, the command in PROMPT_COMMAND will be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM