ps图做ppt模板下载网站,关于旅游案例的网站,前几年做那些网站能致富,外包网站多少钱和其它编程语言类似#xff0c;Shell 也支持选择结构#xff0c;并且有两种形式#xff0c;分别是 if else 语句和 case in 语句。本节我们先介绍 if else 语句#xff0c;case in 语句将会在《Shell case in》中介绍。如果你已经熟悉了C语言、Java、JavaScript 等其它编程…和其它编程语言类似Shell 也支持选择结构并且有两种形式分别是 if else 语句和 case in 语句。本节我们先介绍 if else 语句case in 语句将会在《Shell case in》中介绍。如果你已经熟悉了C语言、Java、JavaScript 等其它编程语言那么你可能会觉得 Shell 中的 if else 语句有点奇怪。if 语句最简单的用法就是只使用 if 语句它的语法格式为if conditionthenstatement(s)ficondition是判断条件如果 condition 成立(返回“真”)那么 then 后边的语句将会被执行如果 condition 不成立(返回“假”)那么不会执行任何语句。从本质上讲if 检测的是命令的退出状态我们将在下节《Shell退出状态》中深入讲解。注意最后必须以fi来闭合fi 就是 if 倒过来拼写。也正是有了 fi 来结尾所以即使有多条语句也不需要用{ }包围起来。如果你喜欢也可以将 then 和 if 写在一行if condition; thenstatement(s)fi请注意 condition 后边的分号;当 if 和 then 位于同一行的时候这个分号是必须的否则会有语法错误。实例1下面的例子使用 if 语句来比较两个数字的大小#!/bin/bashread aread bif (( $a $b ))thenecho a和b相等fi运行结果84↙84↙a和b相等在《Shell (())》一节中我们讲到(())是一种数学计算命令它除了可以进行最基本的加减乘除运算还可以进行大于、小于、等于等关系运算以及与、或、非逻辑运算。当 a 和 b 相等时(( $a $b ))判断条件成立进入 if执行 then 后边的 echo 语句。实例2在判断条件中也可以使用逻辑运算符例如#!/bin/bashread ageread iqif (( $age 18 $iq 60 ))thenecho 你都成年了智商怎么还不及格echo 来C语言中文网(http://c.biancheng.net/)学习编程吧能迅速提高你的智商。fi运行结果20↙56↙你都成年了智商怎么还不及格来C语言中文网(http://c.biancheng.net/)学习编程吧能迅速提高你的智商。就是逻辑“与”运算符只有当两侧的判断条件都为“真”时整个判断条件才为“真”。熟悉其他编程语言的读者请注意即使 then 后边有多条语句也不需要用{ }包围起来因为有 fi 收尾呢。if else 语句如果有两个分支就可以使用 if else 语句它的格式为if conditionthenstatement1elsestatement2fi如果 condition 成立那么 then 后边的 statement1 语句将会被执行否则执行 else 后边的 statement2 语句。举个例子#!/bin/bashread aread bif (( $a $b ))thenecho a和b相等elseecho a和b不相等输入错误fi运行结果10↙20↙a 和 b 不相等输入错误从运行结果可以看出a 和 b 不相等判断条件不成立所以执行了 else 后边的语句。if elif else 语句Shell 支持任意数目的分支当分支比较多时可以使用 if elif else 结构它的格式为if condition1thenstatement1elif condition2thenstatement2elif condition3thenstatement3……elsestatementnfi注意if 和 elif 后边都得跟着 then。整条语句的执行逻辑为如果 condition1 成立那么就执行 if 后边的 statement1如果 condition1 不成立那么继续执行 elif判断 condition2。如果 condition2 成立那么就执行 statement2如果 condition2 不成立那么继续执行后边的 elif判断 condition3。如果 condition3 成立那么就执行 statement3如果 condition3 不成立那么继续执行后边的 elif。如果所有的 if 和 elif 判断都不成立就进入最后的 else执行 statementn。举个例子输入年龄输出对应的人生阶段#!/bin/bashread ageif (( $age 2 )); thenecho 婴儿elif (( $age 3 $age 8 )); thenecho 幼儿elif (( $age 9 $age 17 )); thenecho 少年elif (( $age 18 $age 25 )); thenecho 成年elif (( $age 26 $age 40 )); thenecho 青年elif (( $age 41 $age 60 )); thenecho 中年elseecho 老年fi运行结果119成年运行结果2100老年再举一个例子输入一个整数输出该整数对应的星期几的英文表示#!/bin/bashprintf Input integer number: read numif ((num1)); thenecho Mondayelif ((num2)); thenecho Tuesdayelif ((num3)); thenecho Wednesdayelif ((num4)); thenecho Thursdayelif ((num5)); thenecho Fridayelif ((num6)); thenecho Saturdayelif ((num7)); thenecho Sundayelseecho errorfi运行结果1Input integer number: 4Thursday运行结果2Input integer number: 9error