Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash compare a command output to string [duplicate]

Tags:

bash

git-bash

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

like image 724
Shahid Chaudhary Avatar asked Feb 05 '26 20:02

Shahid Chaudhary


2 Answers

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
like image 186
Gilles Quenot Avatar answered Feb 07 '26 11:02

Gilles Quenot


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

Simple old fashion

This syntax is POSIX compatible, not bash 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 (posix 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
like image 35
F. Hauri Avatar answered Feb 07 '26 11:02

F. Hauri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!