zoukankan      html  css  js  c++  java
  • Linux有关Shell中if用法笔记

    4418040-2a1dddb9b1ab80ee

    shell中的if主要是用于程序的判断逻辑,从而控制脚本的执行逻辑。这和很多编程语言思路上都是一致的。

    1、if的用法结构如下:

    if exp;then

    command1;

    command2;

    fi

    示例:

    #根据输入的学生成绩打印对应的成绩等级:大于90分为优秀;大于80分良好,60到80分为及格;小于60分为差。

    cat test.sh

    #!/bin/bash

    read -p "请输入分数:" Score

    if [ "$Score" -ge 90 ]; then

    echo "优秀"

    fi

    if [ "$Score" -ge 80 ]; then

    echo "良好"

    fi

    if [ "$Score" -ge 60 -a "$Score" -lt 80 ]; then

    echo "及格"

    fi

    if [ "$Score" -lt 60 ]; then

    echo "差"

    fi

    运行如下:输入:88

    输出:良好

    输入:99

    输出:优秀

    2、if/else结构用法

    语法结构:

    if exp; then

    command

    else 

    command

    fi

    示例:#判断某个文件是否存在

    cat checkfile.sh

    脚本内容如下:

    #!/bin/bash

    fl=/root/hgm/bash.sh

    f2=/root/hgm/bash00.sh

    if [ -e $f1 ];then

    echo "$f1 存在"

    else

    echo "$f1 不存在"

    fi

    if [ -e $f2 ];then

    echo "$f2 存在"

    else

    echo "$f2 不存在"

    fi

    bash checkfile.sh

    输出结果:

     存在

    /root/hgm/bash00.sh 不存在

    2、if/elif/else结构用法

    语法格式:

    if exp1; then

    command1

    elseif exp2;then

    command2

    elseif exp3;then

    command3

    ...

    fi

    具体用法和上面两种很相似不再举例说明

  • 相关阅读:
    Leetcode Plus One
    Leetcode Swap Nodes in Pairs
    Leetcode Remove Nth Node From End of List
    leetcode Remove Duplicates from Sorted Array
    leetcode Remove Element
    leetcode Container With Most Water
    leetcode String to Integer (atoi)
    leetcode Palindrome Number
    leetcode Roman to Integer
    leetcode ZigZag Conversion
  • 原文地址:https://www.cnblogs.com/hgmyz/p/12351142.html
Copyright © 2011-2022 走看看