如何关键字“如果”测试值的假是真的吗? [英] how the keyword “if” test the value true of false?
本文介绍了如何关键字“如果”测试值的假是真的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在bash脚本
如果[1]
然后
回声是
其他
回声否
科幻
输出:是
它重新present的1为真值对待。
但在code:
字= Linux的
信= nuxi
如果回声$字| grep的-q$信
然后
回声是
其他
回声否
科幻
输出:无
但回声$字| grep的-q$信
将返回1,为什么结果是否定的。
如何关键字,如果试如果后,由命令返回的值?
解决方案
一个命令的返回值进行检查。 [1]
的 0
的返回值(true)。其他任何返回值(如 1
)指示错误。
您可以使用 $
变量显示上次执行的命令的返回值:
真
回声$?
#返回0
假
回声$?
#返回1
回声$?
#返回0作为最后一个执行的命令是'回声',而不是'假'
In bash script
if [ 1 ]
then
echo "Yes"
else
echo "No"
fi
Output: Yes It represent that '1' is treated as true value.
But in code:
word = Linux
letter= nuxi
if echo "$word" | grep -q "$letter"
then
echo "Yes"
else
echo "No"
fi
Output:No
But echo "$word" | grep -q "$letter"
will return 1, why the result is No.
how the keyword "if" test the value returned by the command after "if"?
解决方案
The return value of a command is checked. [ 1 ]
has a return value of 0
(true). Any other return value (like 1
) indicates an error.
You can display the return value of the last executed command using the $?
variable:
true
echo $?
# returned 0
false
echo $?
# returned 1
echo $?
# returned 0 as the last executed command is 'echo', and not 'false'
这篇关于如何关键字“如果”测试值的假是真的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文