[英]Unexpected output in bash shell script
For the below script I am expecting the output to be msg_y and msg_z
. 对于以下脚本,我期望输出为msg_y and msg_z
。 But it is printing msg_x and msg_z
. 但是它正在打印msg_x and msg_z
。 Can somebody explain to me what is going on? 有人可以向我解释发生了什么吗?
#!/bin/bash
set -x
vr=2
echo $vr
if [ $vr > 5 ]
then
echo "entered 1st if"
echo "msg_x"
echo "out of 1st if"
if [ $vr < 8 ]; then
echo "in of 2nd if"
echo "msg_y"
else
echo "msg_z"
fi
else
if [ $vr > 1 ]; then echo "msg_y"
else echo "msg_z"
fi
fi
This expression 这个表达
[ $vr > 5 ]
is being parsed as an output redirection; 被解析为输出重定向; check to see if you have a file named "5" now. 检查您现在是否有一个名为“ 5”的文件。 The output redirection is vacuously true. 输出重定向完全是虚假的。 Note that the usual admonition to quote parameters inside a test expression would not help here (but it's still a good idea). 请注意,通常不建议在测试表达式中使用引号,但这在这里无济于事(但这仍然是一个好主意)。
You can escape the >
so that it is seen as an operator in the test command: 您可以转义>
以便在测试命令中将其视为运算符:
if [ "$vr" \> 5 ]; then
or you can use the integer comparison operator -gt
或者您可以使用整数比较运算符-gt
if [ "$vr" -gt 5 ]; then.
Since you are using bash
, you can use the more robust conditional expression 由于您正在使用bash
,因此可以使用更强大的条件表达式
if [[ $vr > 5 ]]; then
or 要么
if [[ $vr -gt 5 ]]; then
or use an arithmetic expression 或使用算术表达式
if (( vr > 5 )); then
to do your comparisions (likewise for the others). 做比较(其他人也一样)。
Note: although I showed how to make >
work as a comparison operator even when surrounded by integers, don't do this. 注意:尽管我展示了如何使>
用作比较运算符,即使它被整数包围,也不要这样做。 Most of the time, you won't get the results you want, since the arguments are compared lexicographically, not numerically. 在大多数情况下,您将无法获得所需的结果,因为参数是按字典顺序而不是数字方式进行比较。 Try [ 2 \\> 10 ] && echo What?
尝试[ 2 \\> 10 ] && echo What?
Either use the correct integer comparison operators ( -gt
et al.) or use an arithmetic expression. 使用正确的整数比较运算符( -gt
等)或使用算术表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.