2024年运维最全第十六周-day66-67—Shell编程day03-04


练习题—3



5. 函数

函数名的定义规则和变量是一样:数字、字母、下划线、但是不能以数字开头
5.1 写函数的三种方法
[root@shell day04]# cat test1.sh
#!/bin/bash
##############################################################
# File Name: test1.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#第一种方法
#定义函数,函数加载到内存
function hello(){
    echo "hello oldchang"
    # return n
}
#使用函数
hello

#第二种方法
function hello2 {
    echo "hello2 2oldboychang"
}
hello2

#第三种方法
hello3(){
    echo "hello3 3oldoychang"
}
hello3
[root@shell day04]# sh test1.sh
hello oldchang
hello2 2oldboychang
hello3 3oldoychang

可以在函数下一起调用

5.2 优先调用函数

[root@shell day04]# touch hello
[root@shell day04]# chmod +x hello 
[root@shell day04]# echo hello >hello 
[root@shell day04]# ll
total 8
-rwxr-xr-x 1 root root   6 Jul 18 10:00 hello
-rw-r--r-- 1 root root 501 Jul 18 09:57 test1.sh
[root@shell day04]# 
[root@shell day04]# source /server/scripts/day04/test1.sh 
hello oldchang
hello2 2oldboychang
hello3 3oldoychang
[root@shell day04]# hello #优先调用了函数
hello oldchang	

5.3 函数的退出状态码

脚本的退出状态码,使用exit定义,之后脚本退出

函数的退出状态码,使用return定义,之后函数退出

[root@shell day04]# vim test1.sh 
  1 #!/bin/bash 
  2 ##############################################################
  3 # File Name: test1.sh
  4 # Version: V1.0
  5 # Author: lcx
  6 # Organization: www.oldboyedu.com
  7 ##############################################################
  8 #
  9 #
 10 function hello(){
 11     if [ -f "/etc/hosts" ];then
 12         echo "文件存在"
 13     else
 14         return 2
 15     fi
 16 }
 17 hello
 18 echo $?
[root@shell day04]# sh test1.sh 
文件存在
0

5.4 带参数的函数

[root@shell day04]# vim test2.sh 
  1 #!/bin/bash
  2 function hello {
  3     echo "hello $1"
  4 }
  5 hello $1
[root@shell day04]# sh test2.sh oldboy
hello oldboy

[root@shell day04]# vim test2.sh 
  1 #!/bin/bash
  2 function hello {
  3    echo "hello $1 $2"	#定义2个参数
  4 }                                                                           
  5 hello $1 $2
[root@shell day04]# sh test2.sh oldboy oldchang
hello oldboy oldchang

5.5 位置函数
[root@shell day04]# cat test3.sh 
#!/bin/bash
function hello {
   echo "hello $\*"
}
hello $# $1 "$\*"
[root@shell day04]# sh test3.sh 1 2 3
hello 3 1 1 2 3

第二种方法,也是最常用的方法

[root@shell day04]# cat test3.sh 
#!/bin/bash
function hello {
   echo "脚本名称: $0"
   echo "函数的参数个数: $#"
   echo "第一个参数: $1"
   echo "显示所有参数: $\*"
   echo "执行状态码: $?"
}
hello $\*
[root@shell day04]# sh test3.sh 1 2 3 4 5
脚本名称: test3.sh
函数的参数个数: 5
第一个参数: 1
显示所有参数: 1 2 3 4 5
执行状态码: 0

作业:将nginx启动脚本修改为函数格式


6.case语句



6.1 case条件语句练习

[root@shell day04]# cat case1.sh
#!/bin/bash
##############################################################
# File Name: case1.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
case "$1" in
    "start"|"START")
        echo "已启动"
        ;;
    "stop"|"STOP")
        echo "已停止"
        ;;
    *)
        echo "你tm说的啥"
esac
 [root@shell day04]# sh case1.sh start
已启动
[root@shell day04]# sh case1.sh stop
已停止
[root@shell day04]# sh case1.sh xxx
你tm说的啥
[root@shell day04]# sh case1.sh START
已启动
[root@shell day04]# sh case1.sh STOP
已停止

练习题

6.2 练习

6.2.1 使用case判断是数字还是字母

编写脚本,使用单个字符进行传参,使用case判断是数字还是字母

[root@shell day04]# cat case2.sh 
#!/bin/bash
##############################################################
# File Name: case1.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
case "$1" in
    [0-9])
        echo "这是数字$1"
        ;;
    [a-Z])
        echo "这是字母$1"
        ;;
    *)
        echo "你tm输的啥"
        exit
esac

[root@shell day04]# sh case2.sh v
这是字母v
[root@shell day04]# sh case2.sh A
这是字母A
[root@shell day04]# sh case2.sh 5
这是数字5
[root@shell day04]# sh case2.sh 0
这是数字0

6.2.2 将” 打印菜单修改成case或if语句

2、 将” 打印菜单,按照选择项一键安装不同的web服务”脚本,将其中的条件表达式修改成case或if语句

#case语句

[root@shell day04]# cat web.sh 
#!/bin/bash
##############################################################
# File Name: zuoye02.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#检测脚本是否存在且非空,是否可执行
file1=`[ -s /server/scripts/lamp.sh ]&& echo ture||echo fluse`
file2=`[ -s /server/scripts/lnmp.sh ]&& echo ture||echo fluse`
exec1=`[ -x /server/scripts/lamp.sh ]&& echo ture||echo fluse`
exec2=`[ -x /server/scripts/lnmp.sh ]&& echo ture||echo fluse`
case "$file1" in
    ture)
        echo -e "\033[32mlamp.sh脚本文件存在且非空\033[0m"
        ;;
    *)
        echo -e "\033[31mlamp.sh脚本文件不存在或是一个空文件!!!\033[0m"
    esac
case "$exec1" in
    ture)
        echo -e "\033[32mlamp.sh脚本文件可以执行\033[0m"
        ;;
    *)
        echo -e "\033[31mlamp.sh脚本文件不可执行!!!\033[0m"
    esac
case "$file2" in
    ture)
        echo -e "\033[32mlnmp.sh脚本文件存在且非空\033[0m"
        ;;
    *)
        echo -e "\033[31mlnmp.sh脚本文件不存在或是一个空文件!!!\033[0m"
    esac
case "$exec2" in
    ture)
        echo -e "\033[32mlnmp.sh脚本文件可以执行\033[0m"
        ;;
    *)
        echo -e "\033[31mlnmp.sh脚本文件不可执行!!!\033[0m"
esac
#打印菜单,按照选择项一键安装不同的web服务
cat << EOF
 `echo -e "\033[35m (1).[install lamp]\033[0m"`
 `echo -e "\033[36m (2).[install lnmp]\033[0m"`
 `echo -e "\033[33m (3).[exit]\033[0m"`
EOF

read -p "please input the num you want:" num
#安装lamp与lnmp环境
case "$num" in
    1)
        echo start installing LAMP
        sleep 1
        /server/scripts/lamp.sh
        exit
        ;;
    2)
        echo start installing LNMP
        sleep 1
        /server/scripts/lnmp.sh
        exit
        ;;
    3)
        echo 即将退出脚本...
        sleep 1
        exit
        ;;
    *)
        echo Input Error输入不识别!,启动自毁程序...
        sleep 2
        echo 再见人类......
        sleep 2
        exit
esac

#if语句

[root@shell day04]# cat /server/scripts/day03/zuoye02.sh 
#!/bin/bash
##############################################################
# File Name: zuoye02.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#检测脚本是否存在且非空,是否可执行
file1=`[ -s /server/scripts/lamp.sh ]&& echo ture||echo fluse`
file2=`[ -s /server/scripts/lnmp.sh ]&& echo ture||echo fluse`
exec1=`[ -x /server/scripts/lamp.sh ]&& echo ture||echo fluse`
exec2=`[ -x /server/scripts/lnmp.sh ]&& echo ture||echo fluse`
if [ $file1 = "ture" ];then
        echo "lamp.sh脚本文件存在且非空"
    else 
        echo "lamp.sh脚本文件不存在或是一个空文件!!!"
    fi
if [ $exec1 = "ture" ];then
        echo lamp.sh脚本文件可以执行
    else
        echo lamp.sh脚本文件不可执行!!!
    fi
if [ $file2 = "ture" ];then
        echo lnmp.sh脚本文件存在且非空
    else
        echo lnmp.sh脚本文件不存在或是一个空文件!!!
    fi
if [ $exec2 = "ture" ];then
        echo lnmp.sh脚本文件可以执行
    else
        echo lnmp.sh脚本文件不可执行!!!
        exit
    fi
#打印菜单,按照选择项一键安装不同的web服务
cat << EOF
 `echo -e "\033[35m (1).[install lamp]\033[0m"`
 `echo -e "\033[36m (2).[install lnmp]\033[0m"`
 `echo -e "\033[34m (3).[exit]\033[0m"`
EOF

read -p "please input the num you want:" num
#安装lamp环境
if [ $num = "1" ];then
    echo start installing LAMP
    sleep 1
    /server/scripts/lamp.sh
    exit
elif [ $num = "2" ];then
    echo start installing LNMP
    sleep 1
    /server/scripts/lnmp.sh
    exit
elif [ $num = "3" ];then
    echo 即将退出脚本...
    sleep 1
    exit
elif [ $num != "{1..3}" ];then
    echo Input Error输入不识别!,启动自毁程序...
    sleep 2
    echo 再见人类......
    sleep 2
    exit
fi

6.3 将Nginx服务改为case方式+函数方式

3、 将Nginx服务管理脚本改为case方式+函数方式,并通过systemctl进行控制启动停止

先将nginx编译好

yum install -y gcc-c++ pcre-devel zlib-devel	#下载依赖
tar xf nginx-1.17.1.tar #解压到当前目录
cd nginx-1.17.1/	#切换到解压后的目录下
./configure --prefix=/usr/local/nginx	#路径随意
make && make install

[root@shell ~]# ll /usr/local/nginx/sbin/nginx 
-rwxr-xr-x 1 root root 3830336 Jul 18 09:19 /usr/local/nginx/sbin/nginx
[root@shell ~]# cd /etc/init.d/
[root@shell init.d]# touch nginx
[root@shell init.d]# chmod +x nginx

#if方式+函数方式

[root@shell init.d]# vim nginx #
#!/bin/bash
##############################################################
# File Name: nginx.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
if [ "$1" = "start" ];then
    nginx
    echo "nginx服务启动成功"
fi
if [ "$1" = "stop" ];then
#查看当前nginx进程是否存在,非0则存在
    if [ `ss -lntup|grep nginx|wc -l` -eq 0 ];then
        echo "nginx处于关闭状态"
    else
        pkill nginx
    fi
fi
if [ "$1" = "restart" ];then
#先关闭
    if [ `ss -lntup|grep nginx|wc -l` -eq 0 ];then
        echo "nginx处于关闭状态"
    else
        pkill nginx
        sleep 1
    fi
    nginx
    echo "nginx服务重启成功"
fi

#case方式+函数方式




#为nginx添加systemd启动文件
[root@shell init.d]# cd /usr/lib/systemd/system
[root@shell system]# cat nginx\_oldboy.service 
[Unit]
Description=nginx service
After=nginx_oldboy.target

[Service]
Type=forking
ExecStart=/etc/init.d/nginx start
ExecReload=/etc/init.d/nginx restart
ExecStop=/etc/init.d/nginx stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target

#检查是否可以启动关闭重启
[root@shell system]# ss -lntup|grep nginx
[root@shell system]# systemctl start nginx\_oldboy.service #启动
[root@shell system]# ss -lntup|grep nginx
tcp    LISTEN     0      128       *:80                    *:*                   users:(("nginx",pid=15894,fd=6),(nginx",pid=15893,fd=6))
[root@shell system]# systemctl stop nginx\_oldboy.service #关闭
[root@shell system]# ss -lntup|grep nginx
[root@shell system]# systemctl restart nginx\_oldboy.service #重启
[root@shell system]# ss -lntup|grep nginx
tcp LISTEN 0 128 \*:80 \*:\* users:(("nginx",pid=15926,fd=6),(nginx",pid=15925,fd=6))

6.4 使用case选择水果,打印水果名及其颜色

1、 使用case选择水果,并打印水果名及其颜色

#给到的要求与条件
  1.apple
  2.pear
  3.banana
  4.blueberry
其中,颜色表达式分别为
31m 红色
32m 绿色
33m 黄色
34m 蓝色
使用方式为
[root@oldboy-node101 ~]# echo -e "\E[1;31m我是红色 \E[0m"
我是红色 
[root@oldboy-node101 ~]# echo -e "\E[1;32m我是绿色 \E[0m"
我是绿色 
[root@oldboy-node101 ~]# echo -e "\E[1;33m我是黄色 \E[0m"
我是黄色 
[root@oldboy-node101 ~]# echo -e "\E[1;34m我是蓝色 \E[0m"
我是蓝色
1)打印菜单
2)使用read,显示一句话“选择你喜欢的水果”
3)使用case判断数字是【1|2|3|4】
4)如果都不符合,报错退出



7.while循环

7.1 while语法

7.2 while按行读入文件

练习
处于学习阶段,欢迎补充更完美的答案

1.while循环从1加到100,然后再额外使用两种方式计算

2.while循环读入数据,计算文件内的年龄平均值

3.将第6章的练习1,改为死循环的形式。菜单中加入选项exit,只有输入exit才能退出

1.while循环从1加到100,然后再额外使用两种方式计算

[root@shell day04]# cat while3.sh
#!/bin/bash
##############################################################
# File Name: while3.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#while循环从1加到100,然后再额外使用两种方式计算
a=0
while [ $a -lt 100 ];do
    let a++
    echo $a
done
[root@shell day04]# sh while3.sh
1
2
3
4
...
100

#第二种
[root@shell day04]# echo "(1+100)\*100/2"|bc
5050

2.while循环读入数据,计算文件内的年龄平均值

[root@shell day04]# cat age.txt 
jiaojiao 20
yingqian 20
jiangyuan 25
xiaolu 30
xuxu 18
dingsheng 38
lili 5
[root@shell day04]# cat while4.sh 
#!/bin/bash
##############################################################
# File Name: while3.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#计算平均年龄,文件是/server/scripts/age.txt
#a=echo `cat age.txt|awk '{print $2}'`
sum=0
count=0
while read line;do
    age=`echo $line|awk '{print $2}'`
    let sum=${sum}+${age}
    let count++
done  < $1
echo "$sum/$count"|bc
[root@shell day04]# sh while4.sh age.txt
22

3.将第6章的练习1,改为死循环的形式。菜单中加入选项exit,只有输入exit才能退出

[root@shell day04]# cat caidan.sh 
#!/bin/bash
#打印菜单,按照选择项选择你喜欢的人物
prefix="I guess you like "
#菜单
while true ;do
cat << EOF
 `echo -e "\033[32m 1.棋王\033[0m"`
 `echo -e "\033[33m 2.女神\033[0m"`
 `echo -e "\033[34m 3.娘炮\033[0m"`
 `echo -e "\033[35m 4.铁人\033[0m"`
 `echo -e "\033[36m 5.退出\033[0m"`
EOF
read -p "please input the num you like: " num
if [ $num = "1" ];then
        echo "$prefix"黑嘉嘉
    elif [ $num = "2" ];then
        echo "$prefix"高圆圆
    elif [ $num = "3" ];then
        echo "$prefix"打篮球的那个蔡徐坤? Are You OK??
    elif [ $num = "4" ];then
        echo "$prefix"鹿晗...
    elif [ $num = "5" ];then
        echo "即将退出..."
        sleep 1
        exit
    else
        echo "输入错误!请重新输入"
    fi
done

最后的话

最近很多小伙伴找我要Linux学习资料,于是我翻箱倒柜,整理了一些优质资源,涵盖视频、电子书、PPT等共享给大家!

资料预览

给大家整理的视频资料:

给大家整理的电子书资料:

如果本文对你有帮助,欢迎点赞、收藏、转发给朋友,让我有持续创作的动力!

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以点击这里获取!

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
echo "$prefix"打篮球的那个蔡徐坤? Are You OK??
elif [ n u m = " 4 " ] ; t h e n e c h o " num = "4" ];then echo " num="4"];thenecho"prefix"鹿晗…
elif [ $num = “5” ];then
echo “即将退出…”
sleep 1
exit
else
echo “输入错误!请重新输入”
fi
done



> 
> ![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly91cGxvYWQtaW1hZ2VzLmppYW5zaHUuaW8vdXBsb2FkX2ltYWdlcy8xNjk1MjE0OS0zMjk4NDQ2ZTcxNzlhNGMxLnBuZw)
> 


### 最后的话

最近很多小伙伴找我要Linux学习资料,于是我翻箱倒柜,整理了一些优质资源,涵盖视频、电子书、PPT等共享给大家!

### 资料预览

给大家整理的视频资料:

[外链图片转存中...(img-6VPj1QlR-1714530153465)]

给大家整理的电子书资料:

  

[外链图片转存中...(img-HIZnirVe-1714530153466)]



**如果本文对你有帮助,欢迎点赞、收藏、转发给朋友,让我有持续创作的动力!**

**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化的资料的朋友,可以点击这里获取!](https://bbs.csdn.net/topics/618542503)**


**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
  • 11
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值