2016-09-30 44 views
2

我是新来痛击脚本和尝试写以下简单巴什脚本检查条件

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 

而这按预期工作。

但如果我删除回声“一些字符串”不打印输出:

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状态检查打破了功能之后

回答

2

这是因为if-condition执行?作为bash中的复合语句,即command1; command2以及在测试运算符中不正确使用-z

我会用两个例子中的set -x选项的调试来解释它。

对于成功,这是执行顺序是

++ wait_some 2.2 
++ '[' -z 2.2 ']' 
++ echo some_string 
some_string 

正如你可以看到得到执行这两个条件[ -z 2.2 ]失败。但为什么?由于该字符串的长度不为零(See how -z works),并且该检查正在导致条件失败,应该是[ ! -z 2.2 ]。它并没有结束。

由于您已经使用了一套命令组合,因此您可以使用command1; command2command1失败if-condition,现在command2这只是一个简单的echo运行成功地与正收益代码使得整体if-condition成功,导致正则表达式搜索,你能看到后续echo'ed声明。

现在失败的情况下,从set -x展开的结果看起来像

++ wait_some 2.2 
++ '[' -z 2.2 ']' 

正如你所看到的,在去除echo声明,对于if-condition总体返回码已成为虚假和内部条件根本没有行使。还准备卸下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,并声称该脚本没有任何问题。

+0

它的工作原理,谢谢。 – user3663882

+2

请注意,'-z'测试甚至没有必要;你可以试着将空字符串与正则表达式匹配得很好。空字符串不是数字:) – chepner

+0

@chepner:感谢您的评论。除了不正确的语法之外,不想修改作者的代码。很多改进都是可能的。 :) – Inian