ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

第三章、Linux if case判断语句

2022-07-06 11:35:49  阅读:197  来源: 互联网

标签:case 语句 elif ... echo sentence1 sentence2 Linux fi


if 语句

if then fi

单层,单分支

if condition
then
    sentence1
    sentence2
    ...
fi

eg:

#! /bin/bash

a=3
b=4

if [ "${a}" -le "${b}" ] && [ "${a}" -ne 2 ]
then
        echo "${a} is in the range"
fi

其他格式

if condition; then
    sentence1
    sentence2
    ...
fi

#! /bin/bash

a=3
b=4

if [ "${a}" -le "${b}" ] && [ "${a}" -ne 2 ];then echo "${a} is in the range";fi

if then else fi

if condition
then
    sentence1
    sentence2
    ...
else
    sentence1
    sentence2
fi

他也是有其他形式的缩写的,记得有些地方需要加上分号。

#! /bin/bash

filename='expr.sh'

if [ -e "${filename}" ]; then echo "${filename} exist"; else echo "${filename} not exist"; fi

if then elif then elif then fi

if condition
then
    sentence1
    sentence2
    ...
elif condition
then
    sentence1
    sentence2
elif condition
then
    sentence1
    sentence2
else    # 这个 else 可以不要
    sentence1
    sentence2
fi
#! /bin/bash

a=4
if [ "${a}" -eq 1 ]
then echo "${a}=1"
elif [ "${a}" -eq 2 ]
then echo "${a}=2"
elif [ "${a}" -eq 3 ]
then echo "${a}=3"
else echo "${a} < 1 || ${a} > 3"
fi

case 语句

case "${变量名称}" in
    value1)
        sentence1
        sentence2
        ...
        ;;    # 类似于 C/C++中的 break
    
    value2)
        sentence1
        sentence2
        ...
        ;;    # 类似于 C/C++中的 break    
    *)    # 类似于 C/C++ switch中的 default, * 是模式字符串
        sentence1
        sentence2
        ...
        ;;    # 类似于 C/C++中的 break
esac

上文的value是模式字符串,可以使用通配符,如果一个模式字符串中包含多个模式,需要用|分隔开
实例:

#! /bin/bash

choice=$1
echo "choice = ${choice}"

case "${choice}" in
    "-a"|"-b") echo "${choice} is -a or -b";;
    -[cs]) echo "${choice} is -c or -s";;
    *)    echo "others"
esac

参考文献

欢迎报名Y总的Linux基础课
Linux 教程(第四版) - 孟庆昌

标签:case,语句,elif,...,echo,sentence1,sentence2,Linux,fi
来源: https://www.cnblogs.com/lucky-light/p/16450074.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有