关键字"if"如何测试值是true还是false? [英] How does the keyword “if” test if a value is true or false?
本文介绍了关键字"if"如何测试值是true还是false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在bash脚本中
if [ 1 ]
then
echo "Yes"
else
echo "No"
fi
输出:是
它表示将'1'视为真实值.
It represents that '1' is treated as true value.
但是在代码中:
word = Linux
letter = nuxi
if echo "$word" | grep -q "$letter"
then
echo "Yes"
else
echo "No"
fi
输出:否
但是 echo"$ word" |grep -q"$ letter"
将返回1,所以为什么结果是 No
.
But echo "$word" | grep -q "$letter"
will return 1, so why is the result is No
.
关键字 if
如何测试 if
之后的命令返回的值?
How does the keyword if
test the value returned by the command after if
?
推荐答案
检查命令的返回值. [1]
的返回值是 0
(true).其他任何返回值(例如 1
)都表示错误.
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'
这篇关于关键字"if"如何测试值是true还是false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文