Shell 有三种 if ... else 语句:
1.if ... fi 语句;
2.if ... else ... fi 语句;
3.if ... elif ... else ... fi 语句。
if ... fi 语句
if ... else 语句的语法:
if [ expression ] then Statement(s) to be executed if expression is true fi
注意:expression 和方括号([ ])之间必须有空格,否则会有语法错误。
if ... else ... fi 语句
if ... else ... fi 语句的语法
if [ expression ] then Statement(s) to be executed if expression is true else Statement(s) to be executed if expression is not true fi
if ... elif ... else ... fi 语句
if ... elif ... else ... fi 语句的语法
if [ expression 1 ] then Statement(s) to be executed if expression 1 is true elif [ expression 2 ] then Statement(s) to be executed if expression 2 is true elif [ expression 3 ] then Statement(s) to be executed if expression 3 is true else Statement(s) to be executed if no expression is true fi
配合test的if-else语句
if ... else 语句也经常与 test 命令结合使用,如下所示:
num1=1 num2=2 if test ${num1} -eq ${num2} then echo ‘The two numbers are equal!‘ else echo ‘The two numbers are not equal!‘ fi
时间: 2024-10-13 16:19:05