bash 关键字“if”如何测试一个值是真还是假?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3924182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does the keyword “if” test if a value is true or false?
提问by kit.yang
In bash script
在 bash 脚本中
if [ 1 ]
then
echo "Yes"
else
echo "No"
fi
Output: Yes
输出: Yes
It represents that '1' is treated as true value.
它表示“1”被视为真值。
But in code:
但在代码中:
word = Linux
letter = nuxi
if echo "$word" | grep -q "$letter"
then
echo "Yes"
else
echo "No"
fi
Output: No
输出: No
But echo "$word" | grep -q "$letter"
will return 1, so why is the result is No
.
但是echo "$word" | grep -q "$letter"
会返回 1,那么为什么结果是No
.
How does the keyword if
test the value returned by the command after if
?
关键字如何if
测试后命令返回的值if
?
回答by Lekensteyn
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.
检查命令的返回值。[ 1 ]
返回值为0
(true)。任何其他返回值(如1
)表示错误。
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'
回答by Nick
In unix land, 0 is true and 1 is false.
在 unix 领域,0 为真,1 为假。
For your first example:
对于您的第一个示例:
if [ 1 ]
then
echo "Yes"
else
echo "No"
fi
"If" checks the exit code of the given command for true/false (i.e. zero/non-zero).
“If”检查给定命令的退出代码是否为真/假(即零/非零)。
The square brackets actually invoke the "test" command (see "man test" for more information) and give the exit code to if.
方括号实际上调用了“test”命令(有关更多信息,请参阅“man test”)并将退出代码提供给 if。
"test 1" (or indeed "test any_string") returns true (0) so "Yes" is output.
“test 1”(或者实际上是“test any_string”)返回真(0)所以输出“Yes”。
For your second example, this outputs "No" because "nuxi" isn't found in "Linux", if you change "nuxi" to "nux" (perhaps this was a typo?) and remove the spaces around the = then you will get the behaviour you expect. e.g.
对于您的第二个示例,这将输出“否”,因为在“Linux”中找不到“nuxi”,如果您将“nuxi”更改为“nux”(也许这是一个错字?)并删除 = 周围的空格,那么您将获得您期望的行为。例如
word=Linux
letter=nux
if echo "$word" | grep -q "$letter"
then
echo "Yes"
else
echo "No"
fi
回答by Ibrahim
This is because the grep failed to find the $letter in $word, hence the exit code is 1. Whenever a process in linux return a code other than 0 then it means it failed. 0 means exited successfully. You can verify this by echo "Linux" | grep -d "nuxi"; echo $?
这是因为 grep 未能在 $word 中找到 $letter,因此退出代码为 1。每当 linux 中的进程返回 0 以外的代码时,这意味着它失败了。0 表示成功退出。您可以通过以下方式验证echo "Linux" | grep -d "nuxi"; echo $?
On the other hand in scripting world 0 means false and 1 mean true. So the grep failed to find the word and send 1 as an exit code to if, which took it as a true value.
另一方面,在脚本世界中,0 表示假,1 表示真。因此 grep 未能找到该单词并将 1 作为退出代码发送给 if,后者将其作为真值。