我是bash脚本的新手,并尝试编写以下简单内容
function wait_some {
if [ -z $1 ];
echo some_string
then if ! [[ $1 =~ ^[0-9]+([.][0-9]+)?$ ]];
then
echo "$1 is not a number"
exit 2
else echo "it's a number"
fi
fi
}
wait_some 2.2 //prints some_string and then it's a number
并且这按预期工作。
但是,如果我删除echo“ some string”,它不会输出任何内容:
function wait_some {
if [ -z $1 ];
then if ! [[ $1 =~ ^[0-9]+([.][0-9]+)?$ ]];
then
echo "$1 is not a number"
exit 2
else echo "it's a number"
fi
fi
}
wait_some 2.2 //prints nothing
为什么?为什么echo some_string
在条件检查中断功能后立即删除?
这是因为if-condition
在bash
ie中将其作为复合语句执行command1
。command2
以及-z
在测试操作员中使用不正确。
我将对set -x
两个示例的选项进行调试,以对其进行解释。
为了成功,这就是执行顺序
++ wait_some 2.2
++ '[' -z 2.2 ']'
++ echo some_string
some_string
如您所见,执行两个条件[ -z 2.2 ]
失败。但为什么?由于字符串的长度非零(请参见-z
工作原理),并且检查产生的条件失败,应该是[ ! -z 2.2 ]
。并没有到此为止。
由于合并组命令你已经使用的,command1
; command2
的command1
失败if-condition
,现在command2
这只是一个简单的echo
运行成功地与正收益代码使得整体的if-condition
成功,导致正则表达式搜索,你能看到后续echo'ed
声明。
现在针对失败案例,展开后的结果set -x
看起来像
++ wait_some 2.2
++ '[' -z 2.2 ']'
如您所见,在删除该echo
语句时,的整体返回码if-condition
已变为false,并且内部条件完全没有执行。同样,删除该echo
语句类似于false
在脚本中实际添加一个运算符,例如
if [ -z $1 ];
false
那本来会扩展成
++ wait_some 2.2
++ '[' -z 2.2 ']'
++ false
导致您的病情恶化。脚本应该被编码的理想方式是
#/bin/bash
# See the updated if-condition and code reorganization
function wait_some {
if [ ! -z "$1" ];
then
if ! [[ $1 =~ ^[0-9]+([.][0-9]+)?$ ]];
then
echo "$1 is not a number"
exit 2
else echo "it's a number"
fi
fi
}
wait_some 2.2
关于您的错误的最好的办法是,即使http://www.shellcheck.net/也无法在中识别错误的语法,if-condition
并断言脚本没有任何问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句