10

Output is same, and it always echos need to pull. If I remove the quotes around $text in if condition it throws the too many arguments error.

var="$(git status -uno)" && 

text="On branch master Your branch is up-to-date with 'origin/master'. nothing to commit (use -u to show untracked files)"; 

echo  $var; 
echo  $text; 
if [ "$var" = "$text" ]; then
    echo "Up-to-date"
else
    echo "need to pull"
fi

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
Shahid Chaudhary
  • 890
  • 3
  • 14
  • 25
  • 3
    The output of `git status` is not a single line of text. In general, this is a very brittle approach to scripting git – there is no guarantee that the output of `git status` doesn't change between git versions. A better approach would be using `git status --porcelain` (see [docs](https://git-scm.com/docs/git-status#Documentation/git-status.txt---porcelainltversiongt)). – Benjamin W. Mar 29 '19 at 20:54
  • 1
    When I issue `git status -uno` against an up to date branch the return from `git status` has line feeds in it. Those don't seem to be accounted for in your `$text` variable. – JNevill Mar 29 '19 at 20:54

2 Answers2

17

Better do this, =~ for bash regex :

#!/bin/bash

var="$(git status -uno)" 

if [[ $var =~ "nothing to commit" ]]; then
    echo "Up-to-date"
else
    echo "need to pull"
fi

or

#!/bin/bash

var="$(git status -uno)" 

if [[ $var == *nothing\ to\ commit* ]]; then
    echo "Up-to-date"
else
    echo "need to pull"
fi
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
4

Warning: 's regex require more ressources and won't work in other !

Simple old fashion

This syntax is POSIX compatible, not only!

if LANG=C git status -uno | grep -q up-to-date ; then
    echo "Nothing to do"
else
    echo "Need to upgrade"
fi

Or testing a variable ( too)

From this answer to How to check if a string contains a substring in Bash, here is a compatible syntax, working under any standard POSIX shell:

#!/bin/sh

stringContain() { [ -z "${2##*$1*}" ] && { [ -z "$1" ] || [ -n "$2" ] ;} ; }

var=$(git status -uno)

if  stringContain "up-to-date" "$var" ;then
    echo "Up-to-date"
    # Don't do anything
else
    echo "need to pull"
    # Ask for upgrade, see: 
fi
F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137
  • Closing the question as a duplicate (with the dupehammer, nonetheless) *and* answering it is a bit odd, no? – Benjamin W. Mar 29 '19 at 22:38
  • @BenjaminW. I agree, it was late, I answered spontaneously, then I realized: title of quest stand for *output of a command*, but question itsefl is about a *variable check"... – F. Hauri - Give Up GitHub Mar 30 '19 at 07:45