条件判断:if语句
语法格式:
if [ expression ]thenStatement(s) to be executed if expression is truefi
注意:expression 和方括号([ ])之间必须有空格,否则会有语法错误。
if 语句通过关系运算符判断表达式的真假来决定执行哪个分支。Shell 有三种 if ... else 语句:
if ... fi 语句if ... else ... fi 语句if ... elif ... else ... fi 语句
示例:
#!/bin/bash/a=10b=20if [ $a == $b ]then echo "a is equal to b"elif [ $a -gt $b ]thenecho "a is greater to b"elseecho "a is less to b"fi
if ... else 语句也可以写成一行,以命令的方式来运行:
a=10;b=20;if [ $a == $b ];then echo "a is equal to b";else echo "a is not equal to b";fi;
if ... else 语句也经常与 test 命令结合使用,作用与上面一样:
#!/bin/bash/a=10b=20if test $a == $b then echo "a is equal to b"elseecho "a is not equal to b"fi
分支控制:case语句
case ... esac 与其他语言中的 switch ... case 语句类似,是一种多分枝选择结构。
示例:
#!/bin/bash/grade="B"case $grade in "A") echo "Very Good!";;"B") echo "Good!";;"C") echo "Come On!";;*) echo "You Must Try!"echo "Sorry!";;esac
转换成C语言是:
#include <stdio.h>int main(){char grade = 'B';switch(grade){case 'A': printf("Very Good!");break;case 'B': printf("Very Good!");break;case 'C': printf("Very Good!");break;default: printf("You Must Try!");printf("Sorry!");break;}return 0;}
对比看就很容易理解了。很相似,只是格式不一样。
需要注意的是:
取值后面必须为关键字 in,每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后,其间所有命令开始执行直至 ;;。;; 与其他语言中的 break 类似,意思是跳到整个 case 语句的最后。
取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令。
再举一个例子:
#!/bin/bashoption="${1}"case ${option} in"-f") FILE="${2}"echo "File name is $FILE";;"-d") DIR="${2}"echo "Dir name is $DIR";;*) echo "`basename ${0}`:usage: [-f file] | [-d directory]"exit 1 # Command to come out of the program with status 1;;esac
运行结果:
$./test.shtest.sh: usage: [ -f filename ] | [ -d directory ]./test.sh -f index.htmlFile name is index.html
这里用到了特殊变量${1},指的是获取命令行的第一个参数。
for循环
shell的for循环与c、php等语言不同,同Python很类似。下面是语法格式:
新闻热点
疑难解答