流程控制:if分支结构

来源:互联网 发布:电气控制图绘制软件 编辑:程序博客网 时间:2024/04/30 13:24

shell中if判断语法:

if commands; then    commandselif commands; then     commandselse     commandsfi

与if一块使用的commands比较流行的格式是:
[ expression ]
这里的expression是一个表达式,其执行结果是true或者是false。注意中括号表达式最前面和最后面都是有空格的。
具体文件表达式demo:

#!/bin/bash# test-file :Evaluate the status of a file FILE=~/.bashrcif [ -e "$FILE" ]; then    if [ -f "$FILE" ]; then       echo "$FILE is a regular file."    fi    if [ -d "$FILE" ]; then        echo "$FILE is a directory."    fi    if [ -r "$FILE" ]; then        echo "$FILE is readable."    fi    if [ -w "$FILE" ]; then        echo "$FILE is writable"    fielse        echo "$FILE does not exist"fi                                               

这个脚本会计算赋值给常量file的文件,并显示计算结果。对于此脚本有一点需要注意:在表达式中参数”$FILE“ 是怎么被引用的。引号并不是必需的,但这事为了防范空参数,如果$FILE的参数展开是一个空值,就会导致一个错误(操作符将会被解释为非空的字符串而不是操作符)。
字符串表达式demo:

#!/bin/bash#test-string:evaluate the value of a stringANSWER=maybeif [ -z "$ANSWER" ]; then       echo "There is no answer." >&2       exit 1fiif [ "$ANSWER" == "yes" ]; then   echo "The answer is YES."elif [ "$ANSWER" == "no" ]; then   echo "The answer is NO."elif [ "$ANSWER" == "maybe" ]; then   echo "The answer is MAYBE."else   echo "The answer is UNKOWN"fi

在这个脚本中,我们计算常量ANSWER。我们首先确定字符串是否为空。如果为空,我们就终止脚本,并把退出状态设为零。注意这个应用于echo命令的重定向操作。其把错误信息”There is no answer.”重定向到标准错误,这是处理错误信息的”合理“方法。如果字符串不为空,我们就计算字符串的值,看看它是否等于”yes”,”no”或者“maybe”。为此使用了elif,它是“else if”的简写。
整型表达式demo:

#!/bin/bash#int-testINTVALUE=99if [[ "$INTVALUE" =~ ^-?[0-9]+$ ]]; then   echo "$INTVALUE regular [0-9]"fiif [ -z "$INTVALUE" ]; thenecho "the number is empty" >&2exit 1fiif [ 0 -eq $INTVALUE ]; thenecho "the number equals 0"else    if [ $INTVALUE -gt 0 ]; then     echo "the number is positive"    else      echo "the number is negative"    fi    if [ $(($INTVALUE%2)) -eq 0 ]; then       echo "the num is even"   else       echo "the num is odd"    fifi

这个脚本中通过对2取模后的余数与0比较来判断数字是奇数还是偶数。
在bash版本包括一个复合命令,作为加强的test命令替代物。它的使用语法:

[[ expression ]]

这里expression是一个表达式,其计算结果为真或假。这个[[ ]]命令非常相似于test命令(它所支持所有的表达式),但是增加了一个重要的新的字符串表达式:

string1 =~ regex

如果string1匹配扩展的正则表达式regex,返回为真。这就为执行比如数据验证等任务提供了许多可能性。实例代码:

if [[ "$INTVALUE" =~ ^-?[0-9]+$ ]]; then   echo "$INTVALUE regular [0-9]"fi

除了 [[ ]]复合命令之外,bash也提供了(( ))复合命名,其有利于操作整数。(( ))只处理整数。
综合表达式: && ,|| ,! 含义和java中含义一样。

0 0
原创粉丝点击