zoukankan      html  css  js  c++  java
  • shell编程——条件执行

    我们知道程序无非三种执行方式——顺序、条件、循环。顺序就是一条一条的执行,是一马平川;条件就是个十字路口,根据条件决定自己的走向;循环就是笨驴拉磨,一圈一圈的走,知道达到条件终止。现在集中shell中的条件执行。

    存在两个模式:

    • if...then...fi
    • case...esac

    if...then...fi模式

    基本语法:

    if [ 条件表达式 ]; then
        条件满足时可执行的命令
    fi

    例子:

    提示输入“Y"、“y"、“N"、“n".要是输入的“Y"或“y"则输出”Continue!";要是输入的“N"或“n"则输出”Oh,  You input No!";否则输出“Input Wrong".

    #!bin/bash
    read -p "Please input Y y N or n:" yn
    if [ $yn == Y ] || [ $yn == y ]; then
        echo "Continue!"
        exit 1
    fi
    if [ $yn == N ] || [ $yn == n ]; then
        echo "Oh, You input No!"
        exit 1
    fi
    
    echo "Input Wrong"

    这样看上去有点冗余(比如 exit 1),可以用下面的模式简化

    if [ 条件1 ]; then
        满足条件1时执行1
    elif [ 条件2 ]: then
        满足条件2时执行2
     .
     .
     .
    else
        以上n-1个条件都不满足,执行n
    fi

    这样上面的程序简化下:

    #!bin/bash
    read -p "Please input Y y N or n:" yn
    if [ $yn == Y ] || [ $yn == y ]; then
        echo "Continue!"
    elif [ $yn == N ] || [ $yn == n ]; then
        echo "Oh, You input No!"
    else
        echo "Input Wrong"
    fi

    那么当判断1——12月份时,那不if elif elif........的一大堆了,有一种case....esac模式

    case....esac模式

    case $变量名 in
    ”第1个变量内容“)
             程序段1
             ;;
    ”第2个变量内容“)
             程序段2
             ;;
     .
     .
     .
    *)
             程序段n
             ;; 
    esac

    那就列出月份是属于哪个季度

    #!bin/bash
    read -p "Input the month(1-12):" mon
    case $mon in
    1)
        echo "the first quarter."
        ;;
    2)
        echo "the first quarter."
        ;;
    3)
        echo "the second quarter."
        ;;
    4)
        echo "the second quarter."
        ;;
    5)
        echo "the second quarter."
        ;;
    6)
        echo "the third quarter."
        ;;
    7)
        echo "the third quarter."
        ;;
    8)
        echo "the third quarter."
        ;;
    9)
        echo "the fourth quarter."
        ;;
    10)
        echo "the fourth quarter."
        ;;
    11)
        echo "the fourth quarter."
        ;;
    12)
        echo "the fourth quarter."
        ;;
    *)
        echo "Input Wrong!"
        ;;
    esac
  • 相关阅读:
    [LeetCode] Construct Binary Tree from Inorder and Pretorder Traversal
    [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
    [LeetCode] Candy
    [LeetCode] Next Permutation
    [LeetCode] Permutation Sequence
    [LeetCode] Permutations II
    【转载pku】三十分钟掌握STL
    [LeetCode] Permutations
    【附论文】Facebook推面部识别软件 精准度高达97.25%
    【转载】limits.h
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/2981595.html
Copyright © 2011-2022 走看看