shell编程基础---控制结构

来源:互联网 发布:网络代销商 编辑:程序博客网 时间:2024/05/22 17:36

1. if  语句

     read timeofday

     if [ "$timeofday" = "yes" ] ;then    #给$timeofday 加上“ ”的原因是,避免没有任何输入时,程序运行时报错

        echo "Good morning"

     elif [ "$timeofday" = "no" ] ;then

         echo "Good afternoon"

     else

         echo “Sorry ,$timeofday not recognized .Enter yes or no”

         exit 1

     fi

     exit 0

2.  for 语句

     使用固定字符串的for循环:
             for foo in bar fud 43 ; do

                  echo $foo

             done

      使用通配符扩展的for循环:

            for file in $(ls f*.sh);do

                 echo $file

            done

       类C的for循环:

             for ((i=1;i<=10;i++));do

                   echo -n "$i"

             done

3.while语句

    while [ "$strythis" != "secret"]; do

           echo "Sorry ,try again"

            read trythis

    done

4.until 语句

   until condition ;do

        statements

   done

5.case语句

   case "$timeofday" in

         yes |  y  | Yes | YES )         echo "Goog Morning";;

         n*  | N*)                                echo "Good Afternooon";;

         *)                                           echo "Sorry,answer not recognized"

                                                       echo "Please answer yes or no"

                                                       exit 1

                                                       ;;

    esac

6 命令列表

           AND列表:

                   statement1   &&   statement2   &&   statement3  &&.....

                   从左开始顺序执行每一条命令,如果一条命令返回的时ture,它右边的下一条命令才能执行。如此持续直到有一条命令返回false,则结束

                    例如:

                             if [ -f file_one ]  && echo "Hello" && [ -f file_two ] && echo "there" ; then#z注意,这个地方的执行类似于C语言的if语句执行,直到出现一个flase,就结束

                                  echo "in if"

                             else

                                  echo "in else"

                            fi

             OR列表:

                     statement1 || statement2 || statement3 || ......

                      从左边开始顺序执行每条命令,如果一条命令返回的是flase,它右边的下一条命令才能执行,如此执行知道有一条命令返回ture,或者列表中的所有命令都执行完毕

                              例如:

                                        if [ -f file_one ] || echo "Hello" || echo " there" ;then

                                               echo "in if"

                                                     else

                                                echo "in else"


0 0
原创粉丝点击