5

I have a bash PS1 to get a red color if my git dir is changed or green if not is changed.

if [ $? -eq 0 ]; then \
   echo "$(echo `git status` | grep "nothing to commit" > /dev/null 2>&1; \
   if [ "$?" -eq "0" ]; then \
     # @4 - Clean repository - nothing to commit
     echo "\n'$Green'"$(__git_ps1 "(%s)"'$Color_Off'); \
   else \
     # @5 - Changes to working tree
     echo "\n'$IRed'"$(__git_ps1 "(%s)"'$Color_Off'); \
   fi)\$ "; \
 fi)'

This works fine! But the problem is that in some work dir is very slow because exists many changes and a big diff.

What is the better way to get git status boolean (yes changed or no changed) without a full

I tried with git status --short or git status --porcelain but is very slow yet.

diralik
  • 6,391
  • 3
  • 28
  • 52
moylop260
  • 1,288
  • 2
  • 13
  • 20
  • I'd recommend [posh git](https://github.com/dahlbyk/posh-git) instead of doing this yourself. It does something like you described, but also a lot more. – adrianbanks Feb 13 '16 at 02:01

2 Answers2

5

Perhaps this answer might be useful: https://stackoverflow.com/a/2659808/3903076

In short, you can adapt the checks below to your needs. See the linked answer for more details.

if ! git diff-index --quiet --cached HEAD; then
    # Index has changes.
    exit 1;
elif ! git diff-files --quiet; then
    # Working tree has changes.
    exit 1;
elif [ -n "`git ls-files --others --exclude-standard`" ]; then
    # There are untracked unignored files.
    exit 1;
fi
Lenna
  • 1,220
  • 6
  • 22
filipos
  • 645
  • 6
  • 12
  • this bit ```! git diff-files --quiet; then # Working tree has changes.``` was the one I needed. Thank you! I hope it would work in the future without any breaking changes in git. – pegasuspect Jul 30 '18 at 14:50
0

I found the answer here: https://gist.github.com/sindresorhus/3898739 git diff --quiet --ignore-submodules HEAD 2>/dev/null

This is very faster but if you have a untracked file you will have a changed==0 boolean, but is good to me.

git_ps1_style ()
{
    local GREEN="\001\033[0;32m\002"
    local RED="\001\033[0;91m\002"
    local git_branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null)";
    local git_ps1_style="";
    if [ -n "$git_branch" ]; then
        (git diff --quiet --ignore-submodules HEAD 2>/dev/null)
        local git_changed=$?
        if [ "$git_changed" == 0 ]; then
            git_ps1_style=$GREEN$git_branch;
        else
            git_ps1_style=$RED$git_branch;
        fi
    fi
    echo -e "$git_ps1_style"
}
echo $(git_ps1_style)
moylop260
  • 1,288
  • 2
  • 13
  • 20