十二、流程控制语句

来源:互联网 发布:terrans force s4 知乎 编辑:程序博客网 时间:2024/05/22 15:04

(1)if判断(结束用fi)

if判断:

语法:if 条件then 输出fi
eg:num1=2num2=2if [ ${num1} -eq ${num2} ];then    echo `expr ${num1} \* ${num2}`;fi

if-else判断:

语法:if  条件then 输出else 输出fi
eg:cd /home/dataif test -e ./a.shthen    echo 'The file already exists!'else    echo 'The file does not exists!'fi

if then- else if- else判断:(两次判断)

if  条件then 输出elif 条件then 输出else 输出fi
eg 1:#!/bin/basha=1b=2if [ $a == $b ]thenecho "a等于b"elif [ $a -lt $b ]thenecho "a小于b"elif [ $a -gt $b ]thenecho "a大于b"elseecho "不符合以上所有判断"fi结果:[root@h data]# vi a.sh[root@h data]# chmod +x ./a.sh [root@h data]# ./a.sh a小于b
eg 2:(if与test命令结合使用)----test测试:数值测试可用[];字符串测试必须用{}n1=$[2*4]n2=$[5+3]if test $[n1] -eq $[n2]thenecho "n1等于n2"elseecho "两数字不一样"fi

(2)for循环

语法:for variable in item1 item2 item3....do输出输出....输出done合并成一行:for variable in item1 item2 item3....; do 输出;输出;....;输出;donein后面可以跟任何替换、字符串、文件
eg:echo "--------\例一:$*--------"for i in "$*";doecho $idoneecho "--------\例二:$@--------"for i in "$@";do echo $i;done执行结果:[root@h data]# /bin/sh ./t2.sh "a" "b" "c" "d"--------\例一:a b c d--------a b c d--------\例二:a b c d--------abcd

注:

无限循环for((;;))

(3)while
通常用于处理大量的命令,或是从输入文件中读取数据信息;(命令通常指测试条件)

格式:while 判断条件do输出done
eg 1:#!/bin/bashi=1while(($i<=5))doecho "$i"let "i++"done

无限循环:

(不可用)whiledo输出done或者while truedo输出done
eg 2echo "What's your name?"while read namedoecho "My name is ${name}!"done

(4)until
until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。一般while循环优于until循环,但在某些时候,也只是极少数情况下,until 循环更加有用。

语法:(循环至少执行一次)until 条件do输出done

条件: 一般为条件表达式,如果返回值为 false,则继续执行循环体内的语句,否则跳出循环。

eg:(使用 until 命令输出 0 ~ 9 的数字)#!/bin/bashecho "--------------until--------------------"a=3until [ ! $a -lt 6 ]do   echo $a   a=`expr $a + 1`doneecho "----------------while------------------------"b=5while(($b<=6))do   echo $b   b=`expr $b + 1`done运行结果:[root@h data]# /bin/sh d.sh -------------until--------------------345----------------while-----------------56

(6)case

语法:casein模式1)输出1输出2输出3输出n;;模式2)输出1输出2输出3输出n;;esac
eg:#!/bin/bashecho "输入1到3之间的数字:"echo "亲,输入的数字是:"read numcase $num in1)echo "你选择了1";;2)echo "你选择了2";;3)echo "你选择了3";;*)echo "你没有输入1到3之间的数字";;esac

(7)跳出循环
break和continue:
break命令
跳出所有循环(终止执行后面操作)
continue命令
不跳出所有循环,仅仅跳出当前循环

eg:#!/bin/bashecho "输入1到3之间的数字:"echo "亲,输入的数字是:"read numwhile truedocase $num in1|2|3)echo "你选择了$num";;*)echo "你没有输入1到3之间的数字";continueecho "over!";;esacdone
eg2:#!/bin/bashwhile truedoecho "输出1~5之间的数字:"echo "请输入输出的数字是"read numcase $num in1|2|3|4|5)echo "你选择了$num";;*)echo "只能输入1~5之间的数"continueecho "over!";;esacdone
原创粉丝点击