0

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!

liviubiur
  • 111
  • 3
  • 13
  • 2
    What does "it isn’t working" mean? – mkrieger1 Jul 15 '20 at 21:37
  • When I'm in a git directory it doesn't show me the name of the branch. – liviubiur Jul 15 '20 at 21:45
  • 2
    `if [[...]]; then [\u@\h \W]` will attempt to run a command with the name `[\u@\h`. – William Pursell Jul 15 '20 at 21:45
  • Here's what I do: https://github.com/wrp/dotfiles/blob/master/.bashrc#L74 – William Pursell Jul 15 '20 at 21:46
  • Thanks @WilliamPursell! After edited it like that `PS1="$(if [[ ${EUID} == 0 ]]; then echo '\[\033[01;31m\]\h\[\033[01;34m\] \W'; else echo '\[\033[01;32m\]\u@\h\[\033[01;34m\] \w'; fi) \$([[ \$? != 0 ]] && echo \"\[\033[01;31m\]:(\[\033[01;34m\] \")\\$\[\033[00m\]) \$(if [[git rev-parse --is-inside-work-tree]]; then [\u@\h \W]\[\033[00;32m\]\$(git_branch)\[\033[00m\]\$"` I receive that error `bash: command substitution: line 2: syntax error: unexpected end of file` – liviubiur Jul 15 '20 at 21:54
  • 2
    Also : look for the `__git_ps1` function in the `contrib/` files of your git installation, either in `contrib/completion/git-completion.bash` or in `contrib/completion/git-prompt.sh` – LeGEC Jul 15 '20 at 22:00
  • How can I concatenate it to my actual configuration? – liviubiur Jul 15 '20 at 22:08

1 Answers1

2

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.

UtLox
  • 3,744
  • 2
  • 10
  • 13