bash将命令输出结果与字符串进行比较

Bash compare a command output to string

本问题已经有最佳答案,请猛点这里访问。

输出是相同的,它总是回显need to pull。如果删除if条件中$text周围的引号,就会抛出too many arguments错误。

1
2
3
4
5
6
7
8
9
10
11
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


简单的旧时尚

此语法与POSIX兼容,而不仅仅是bash!

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

或者测试变量(posix也是)

从这个答案到如何检查字符串是否包含bash中的子字符串,这里有一个兼容的语法,可以在任何标准的posix shell下工作:

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/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


最好这样做:

1
2
3
4
5
6
7
8
9
#!/bin/bash

var="$(git status -uno)"

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

1
2
3
4
5
6
7
8
9
#!/bin/bash

var="$(git status -uno)"

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