Bash 将命令输出与字符串进行比较
Bash compare a command output to string
输出是一样的,总是回显need to pull
。
如果我在 if
条件下删除 $text
周围的引号,它会抛出 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
最好这样做,=~
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
或
#!/bin/bash
var="$(git status -uno)"
if [[ $var == *nothing\ to\ commit* ]]; then
echo "Up-to-date"
else
echo "need to pull"
fi
警告: bash's regex require more ressources and won't work in other shell!
简约老款
此语法 POSIX 兼容,而非 bash!
if LANG=C git status -uno | grep -q up-to-date ; then
echo "Nothing to do"
else
echo "Need to upgrade"
fi
或测试变量(posix 也是)
来自 this answer to How to check if a string contains a substring in Bash,这是一个兼容的语法,在 any standard POSIX shell[=31 下工作=]:
#!/bin/sh
stringContain() { [ -z "${2##**}" ] && { [ -z "" ] || [ -n "" ] ;} ; }
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
输出是一样的,总是回显need to pull
。
如果我在 if
条件下删除 $text
周围的引号,它会抛出 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
最好这样做,=~
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
或
#!/bin/bash
var="$(git status -uno)"
if [[ $var == *nothing\ to\ commit* ]]; then
echo "Up-to-date"
else
echo "need to pull"
fi
警告: bash's regex require more ressources and won't work in other shell!
简约老款
此语法 POSIX 兼容,而非 bash!
if LANG=C git status -uno | grep -q up-to-date ; then
echo "Nothing to do"
else
echo "Need to upgrade"
fi
或测试变量(posix 也是)
来自 this answer to How to check if a string contains a substring in Bash,这是一个兼容的语法,在 any standard POSIX shell[=31 下工作=]:
#!/bin/sh
stringContain() { [ -z "${2##**}" ] && { [ -z "" ] || [ -n "" ] ;} ; }
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