day61-linux-shell-函数

day61-linux-shell函数

1.函数基本概述

  1. 什么是shell函数

    函数是一对命令的合集,用来完成特定功能的代码块

2为什么要使用函数

我们经常需要使用判断功能,完全可以将其封装为一个函数,这样在写程序中可以在任何地方调用该函数,不必重复编写.这样能减少代码冗余,可读性强.

函数和变量类似,必须先定义才可以调用,如果定义不调用则不会被执行.

3.函数的基础语法

定义函数:有两种方法

#第一种
fun() {
    echo "123"
}

#第二种方式
function fun_status { 
    echo "456"
}
    echo "This is Number: $(fun)"
    
#调用函数
方法一:fun
方法二:fun_status

4.函数状态返回码

shell的函数返回值,也算是退出的退出的状态.在shell中只有echo ,return两种方式.

  1. return返回值:只能返回1-255的整数,函数使用return返回值,通常只是用来供其他地方调用获取状态,因此通常仅返回0或1 ;0表示成功,1表示失败

  2. echo返回值:使用echo可以返回任何字符串结果,通常用于返回数据,比如一个字符串值或者列表值

    函数实例脚本: echo
    echo "The 1 user is : root"
    echo "The 2 user is : bin"
    
    [root@manager functions]# cat fun06.sh 
    #!/bin/bash
    # Author:      Oldux.com QQ: 552408925
    # Date:       2019-11-04
    # FileName:   fun06.sh
    # URL:         https://www.xuliangwei.com
    # Description: 
    
    get_users () {
     user=$(awk -F ":" '{print $1}' /etc/passwd)
     echo $user
    }
    
    #将函数输出的结果,从新赋值给user_list变量存储起来
    user_list=$(get_users)
    
    index=1
    for u in ${user_list}
    do
     echo "The $index user is : $u"
     let index++
    done
    

函数的传参:

  1. 如何给函数传递一个参数

    fun01 () { echo "Hello $1"; } 
    fun01 SHell          #执行时跟上一个固定的参数
    fun01 $1         #执行时跟上一个不固定的参数    (脚本的位置参数,需要执行脚本时传递)
    
    
  2. 函数接收N多个参数传递

fun01 () { echo "Hello $*"; } 
fun01 liunx shell  Python  Test
  1. 函数传参

    第一种方式
    fun01 () {
     echo "Hello $1"
    }
    
    #脚本的位置参数
    fun01 $1
    

    需求:写一个脚本实现nginx的启动,停止,重启

    1. 先实现启动和停止

    2. 优化脚本

      ngx_status=$1
      
      nginx_is_status () {
        
        systemctl $ngx_status nginx
        if [ $? -eq 0 ];then
            echo "nginx is $ngx_status"
        else
            echo "nginx is $ngx_stauts err"
            exit 1
        fi
      }
      
      case $ngx_status in
        start)
            nginx_is_status
            ;;
      
        stop)
            nginx_is_status
        ;;
        *)
            echo "USAGE: $0 { start | stop | restart }"
            exit
      esac
      
      

5.函数返回值

函数实例脚本: return

[root@manager functions]# cat fun09.sh 
#!/bin/bash
# Author:      Oldux.com QQ: 552408925
# Date:       2019-11-04
# FileName:   fun09.sh
# URL:         https://www.xuliangwei.com
# Description: 
#根据用户传递的服务名称,获取不同服务的状态
is_server_running(){
    systemctl status $1 &>/dev/null
    if [ $? -eq 0 ];then
        return 0
    else
        return 1
    fi
}
#调用函数,并根据函数返回状态码进行输出
is_server_running $1 && echo "$1 is Running" || echo "$1 is stoped
[root@manager functions]# cat fun07.sh 
#!/bin/bash
# Author:      Oldux.com QQ: 552408925
# Date:       2019-11-04
# FileName:   fun07.sh
# URL:         https://www.xuliangwei.com
# Description:
file=$1            #定义文件

t_file(){                   #函数判断
    if [ -f $file ];then
        return 0
    else
        return 1
    fi
}

$?
t_file
rc=$?

if [ $rc -eq 0 ];then
    echo "该文件存在 $file"
else
    echo "该文件不存在 $file"
fi
[root@manager functions]# cat fun08.sh 
#!/bin/bash
# Author:      Oldux.com QQ: 552408925
# Date:       2019-11-04
# FileName:   fun08.sh
# URL:         https://www.xuliangwei.com
# Description: 
fun () {
    systemctl status nginx &>/dev/null

    if [ $? -eq 0 ];then
        return 0
    else
        return 100
    fi

}
fun
echo $?
##############################################################
retrun: 主要控制函数的返回值   可以理解是命令执行后的结果
echo:  主要控制函数的返回数据
[root@manager functions]# cat fun09.sh 
#!/bin/bash
# Author:      Oldux.com QQ: 552408925
# Date:       2019-11-04
# FileName:   fun09.sh
# URL:         https://www.xuliangwei.com
# Description: 
#根据用户传递的服务名称,获取不同服务的状态
is_server_running(){
    systemctl status $1 &>/dev/null
    if [ $? -eq 0 ];then
        return 0
    else
        return 1
    fi
}
#调用函数,并根据函数返回状态码进行输出
is_server_running $1 && echo "$1 is Running" || echo "$1 is stoped

6.函数相关示例脚本

需求一: 使用函数,循环,case实现系统管理工具箱.

Command action
h 显示命令帮助
f 显示磁盘分区
d 显示磁盘挂载
m 查看内存使用
u 查看系统负载
q 退出程序
[root@manager functions]# cat fun10.sh 
#!/bin/bash
# Author:      Oldux.com QQ: 552408925
# Date:       2019-11-04
# FileName:   fun10.sh
# URL:         https://www.xuliangwei.com
# Description: 

meminfo () {
cat <<-EOF
----------------------------
    Command action
    h 显示命令帮助
    f 显示磁盘分区
    d 显示磁盘挂载
    m 查看内存使用
    u 查看系统负载
    q 退出程序
---------------------------
EOF
}
    meminfo

while true
do
    read -p "请输出你要选择选项: " Action
    case $Action in 
        h)
            help
            ;;
        f)
            lsblk
            ;;
        d)
            df -h
            ;;
        m)
            free -m
            ;;
        u)
            uptime
            ;;
        q)
            exit
            ;;
        *)
            continue

    esac
done

需求:使用case,循环,函数,实现jumpserver跳板机功能

  1. 用户登录该服务器则会自动执行该脚本.
  2. 脚本提示可连接主机列表
  3. 该脚本无法直接退出
[root@manager functions]# cat fun11.sh 
#!/bin/bash
# Author:      Oldux.com QQ: 552408925
# Date:       2019-11-04
# FileName:   fun11.sh
# URL:         https://www.xuliangwei.com
# Description: 
meminfo(){
        cat <<-EOF
        -------------------------------
        |       1) lb01-172.16.1.5      |
        |       2) lb02-172.16.1.6      |
        |       3) web01-172.16.1.7     |
        |       4) web02-172.16.1.8     |
        |       h) help                 |
        ---------------------------------
    EOF
}
    meminfo
    trap "" HUP INT TSTP

while true
do
    read -p "请输入你要登录的主机: " Action
    
    case $Action in
        1|lb01)
            ssh [email protected]
        ;;
        2|lb02)
            ssh [email protected]
        ;;
        3|web01)
            ssh [email protected]
        ;;
        4|web02)
            ssh [email protected]
        ;;
        h)
            clear
            meminfo
        ;;
        exec)
            exit
            ;;
        *)
            continue
    esac
done

需求:case场景示例,实现多级菜单功能,需要使用函数,case,循环,if判断,变量

info {
    index1: linux
    index2: nginx
    index3: docker
    index4: bash shell
}

[root@manager array]# cat array01.sh 
#!/bin/bash
# Author:      Oldux.com QQ: 552408925
# Date:       2019-11-04
# FileName:   array01.sh
# URL:         https://www.xuliangwei.com
# Description: 

while read line
do
    host[i++]=$line
done 

需求:使用shell数组统计nginx访问日志,统计top10的ip

[root@manager-61 ~/array]#cat array1.sh 
#!/bin/bash
#*********************
#Author: 流星花雨
#QQ: 1679338722
#Date: 2019-11-04
#FileName: array1.sh
#URL: https://www.leitiancheng.cn
#Description: The test script
#*********************
declare -A log
fun () {
while read line
do
    types=$(echo $line|awk '{print $1}')
    let log[$types]++
done 

需求:使用shell数组统计nginx访问日志中的uri

[root@manager-61 ~/array]#cat array2.sh 
#!/bin/bash
#*********************
#Author: 流星花雨
#QQ: 1679338722
#Date: 2019-11-04
#FileName: array2.sh
#URL: https://www.leitiancheng.cn
#Description: The test script
#*********************
declare -A uri
while read line
do
    types=$(echo ${line}|awk '{print $7}')
    let uri[$types]++
done >fj.xuliangwei.com.log
for i in ${!log[@]}
do
    echo 你输入的索引是: $i 该索引出现的此时是: ${uri[$i]}
done

你可能感兴趣的:(day61-linux-shell-函数)