• shell-函数


    shell-函数

    函数定义

    通常shell函数有两种定义方式,如下代码中的fun1和fun2

     1 #!/bin/bash
     2 function fun1(){
     3     echo $1
     4     echo $2
     5 }
     6 
     7 fun2(){
     8     echo "hello"
     9 }
    10 
    11 fun1 1 2
    12 fun2

    说明

    $n代表一个参数,表示传入的第n个参数

    $#表示参数个数

    $*表示传递的参数作为一个字符串显示

    函数返回值

    说明:shell脚本中,函数中的返回值有两种方式

    1)return

    只能返回1~255的整数,一般用来被其他调用获取状态,0表示成功,1表示失败

    2)echo

    可以返回任意字符串,通常用于返回数据

     1 function get_user_info(){
     2     user_info_temp="I am 20"
     3     echo ${user_info_temp}
     4 }
     5 
     6 user_info=`get_user_info`
     7 echo ${user_info}
     8 
     9 function get_nginx_running_status(){
    10     this_script_pid=$$
    11     #一直监控ngnix进程是否在运行
    12 
    13     ps -ef | grep ngnix | grep -v grep | grep -v ${this_script_pid} &> /dev/null
    14     if [ $? -eq 0 ];then
    15         echo "ngnix is runing well"
    16           return 0
    17     else
    18         #启动ngnix进程
    19         systemctl start ngnix
    20         echo "ngnix is down, restart it ..."
    21         return 1
    22     fi
    23 }

    案例

    1)编写一个shell脚本用来监控nginx进程,若nginx进程死掉,则重新启动该进程

     1 function is_nginx_running(){
     2     this_script_pid=$$
     3     #一直监控ngnix进程是否在运行
     4     while true
     5     do
     6         ps -ef | grep ngnix | grep -v grep | grep -v ${this_script_pid} &> /dev/null
     7         if [ $? -eq 0 ];then
     8             echo "ngnix is runing well"
     9             sleep 3
    10         else
    11             #启动ngnix进程
    12             systemctl start ngnix
    13             echo "ngnix is down, restart it ..."
    14         fi
    15     done
    16 }

    注意:

    1)如果不想让日志在前端输出,可以通过nohup sh shell脚本名 &(将输出到nohup.out文件中)

    2)执行 一条grep cmd有返回值时,$?为0,返回为1时则认为nginx程序已死掉

    3)ps -ef | grep nginx 执行时它也会作为一个子进程在电脑中启动起来,对判定条件造成干扰

      ps -ef | grep nginx | grep -v grep 把grep去掉

    4)systemctl stop nginx杀死nginx进程

          systemctl start nginx启动nginx进程

    5)如果shell脚本名中含有nginx,执行脚本本身,脚本也会作为一个进程存在于系统中

    6)$$为在执行就脚本过程中产生的子进程pid输出来,将脚本运行时产生的子进程过滤掉

    函数库

    将逻辑代码或将要复用的代码封装成文件,以便由其他脚本调用

    库文件的后缀是任意的,但一般使用.lib

    库文件一般没有可执行权限

    第一行一般使用#!/bin/echo,输出警告信息,避免用户执行

  • 相关阅读:
    leetcode刷题笔记 217题 存在重复元素
    leetcode刷题笔记 二百零六题 反转链表
    leetcode刷题笔记 二百零五题 同构字符串
    20201119日报
    np.percentile 和df.quantile 分位数
    建模技巧
    np.where() 条件索引和SQL的if用法一样,或者是给出满足条件的坐标集合
    np.triu_indices_from() 返回方阵的上三角矩阵的索引
    ax.set_title() 和 plt.title(),以及df,plot(title='')
    信用卡模型(三)
  • 原文地址:https://www.cnblogs.com/marton/p/12008687.html
Copyright © 2020-2023  润新知