今天继续给大家介绍Linux基础知识,本文主要内容是Linux shell脚本中的选择。
一、shell脚本选择——选择概述
Linux选择语句其实在本质上就是多分支逻辑结构,因此也就可以用if else语句替代,但是Linux shell脚本又为选择的编程逻辑特意设计出了case和select语句,可以使得我们在编写Linux shell脚本的时候更加灵活。
二、shell脚本选择——case语句
case语句语法结构如下所示:
case $A in
Pattern1)
执行语句1;
;;
Pattern2)
执行语句2;
;;
Pattern3)
执行语句3;
;;
……
esac
case语句使用示例如下所示:
#!/bin/bash
# 2021-10-18
# uUthored by pzz
# Used to experiment case sentence
read -p "Please input a char" char
case $char in
[a-Z])
echo "It's a letter"
;;
[0-9])
echo "It's a number"
;;
*)
echo "I don't know"
esac
三、shell脚本选择——select语句
select语句选择菜单的创建,select语句语法结构如下:
select i in (表达式)
do
执行语句
done
select语句的执行语句通常结合case语句连用,这样可以帮助我们快速的实现代码的模块化和类似交互式程序的设计。select语句结合case语句使用示例如下:
#!/bin/bash
# 2021-10-18
# Authored by pzz
# Used to experiment select sentence
echo "Plrease input what you want yo install"
select i in http nginx mysql quit
do
case $i in
http)
echo "The http will be installed"
;;
nginx)
echo "The nginx will be installed"
;;
mysql)
echo "The mysql will be installed"
;;
quit)
echo "Bye!"
exit
esac
done
该脚本执行效果如下:
如果我们写成完整的安装语句,则上述脚本完全可以实现一键式选择安装各种Linux常用软件。
原创不易,转载请说明出处:https://blog.csdn.net/weixin_40228200