Bash比较命令输出和字符串

时间:2019-03-29 20:47:27

标签: bash git-bash

输出是相同的,并且总是回显need to pull。 如果在$text条件下删除if周围的引号,则会引发too many arguments错误。

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 个答案:

答案 0 :(得分:1)

更好地做到这一点:

#!/bin/bash

var="$(git status -uno)" 

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

#!/bin/bash

var="$(git status -uno)" 

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

答案 1 :(得分:1)

简单的旧时尚

此语法与 POSIX 兼容,而不仅限于

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

或测试变量(也

this answer to How to check if a string contains a substring in Bash起,有兼容的语法,可在任何标准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