如何比较bash shell脚本中的变量小于1?如何解决'1:没有这样的文件或目录'
我以前做过,但我得到“1:没有这样的文件或目录”
grep_result=`grep -r $ID . | wc -l`
echo $grep_result
# it said '1: No such file or directory'
if [ $grep_result < 1 ]; then
echo "Wrong id.
exit 1
fi
如何比较bash shell脚本中的变量小于1?如何解决'1:没有这样的文件或目录'
我以前做过,但我得到“1:没有这样的文件或目录”
grep_result=`grep -r $ID . | wc -l`
echo $grep_result
# it said '1: No such file or directory'
if [ $grep_result < 1 ]; then
echo "Wrong id.
exit 1
fi
从bash的角度来看,这意味着管道的文件名为1
到$ grep_result变量。在这种情况下,您需要使用-lt
运算符。 (LE表示小于)
grep_result=`grep -r $ID . | wc -l`
echo $grep_result
# it said '1: No such file or directory'
if [ $grep_result -lt 1 ]; then
echo "Wrong id.
exit 1
fi
这里有两种不同的方式来改变你的代码:
路线#1:
更改您的代码:
grep_result=$(grep -r $ID .)
echo $grep_result
if [ -z "$grep_result" ]; then
echo "Wrong id."
exit 1
fi
说明:
grep_result=$(grep -r $ID .)
:在子shell中运行grep -r $ID .
并将结果输出保存到stdout
至grep_result
。所述$(...)
符号被称为命令替换和优于使用反引号以提高可读性+命令if [ -z "$grep_result" ]; then
的:为[
“测试”壳内置检查是否"$grep_result"
是空字符串的-z
选项;如果是这样,则条件评估为真。路线#2:
,或者:
grep_result_count=$(grep -rc $ID .)
echo $grep_result_count
if [ $grep_result_count -eq 0 ]; then
echo "Wrong id."
exit 1
fi
说明:
grep_result_count=$(grep -rc $ID .)
:类似的想法,但请注意,我们使用-rc
选项代替grep
而不是-r
;该选项的c
部分意味着“不输出匹配的行,只是输出一个数字计数多少匹配,而不是”。因此,在这种情况下,您将得到一个大于或等于0的整数。if [ $grep_result_count -eq 0 ]; then
:此处的-eq
选项检查左边的值是否等于右边的值。在这种情况下,我们是否从之前的grep命令匹配的数目正好等于0您还可以使用一些更高效:
if ! grep -qr "$ID" . ; then
echo "Wrong id."
exit 1
fi
希望这有助于。
随着-q
选项,grep
只是保持安静,只要它的发现模式(如果能找到的话)停止,如果图案被发现输出true
返回值,否则false
。这可能是解决问题的最有效方法。
检查没有匹配的正确方法是
if ! grep -q -r "$ID" . ; then
echo Wrong id.
exit 1
fi
这是正确的:如果if
目的是运行一个命令,并检查它的退出代码。如果匹配,grep
返回成功退出码,否则返回1(错误)。正是出于这个目的,大多数Unix工具都是这样写的。
获得当有匹配的计数是一个小的修改:
if matches=$(grep -r "$ID" .) ; then
echo "$matches" | wc -l
else
echo Wrong Id.
exit 1
fi
注意使用grep -q
只返回一个错误代码,而不是打印出任何东西。如果您只想从单个文件中输出数字(或每个文件的匹配数)grep -c
可以打印该文件。
@AndyLester你说得对。请参阅我的编辑。 –