14

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

2
  • 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). Commented Mar 29, 2019 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. Commented Mar 29, 2019 at 20:54

2 Answers 2

19

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
Sign up to request clarification or add additional context in comments.

3 Comments

bash regex is performance killer!
New script is quicker
What does =~ mean?
6

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

2 Comments

Closing the question as a duplicate (with the dupehammer, nonetheless) and answering it is a bit odd, no?
@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"...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.