• Shell 编程 函数


    CentOS-Logo

    本篇主要写一些shell脚本函数的使用。


    函数调用

    #!/bin/bash
    sum(){
      s=`expr 2 + 3`
      echo $s
    }
    sum
    
    [root@localhost ~]# vim sum.sh
    [root@localhost ~]# chmod +x sum.sh 
    [root@localhost ~]# ./sum.sh 
    5
    

    传递参数

    #!/bin/bash
    sum(){
      s=`expr $1 + $2`
      echo $s
    }
    sum 2 3
    
    [root@localhost ~]# vim sum.sh
    [root@localhost ~]# ./sum.sh 
    5
    

    return

    #!/bin/bash
    sum(){
      return $(($1 + $2))
    }
    sum 2 3
    echo $?
    
    [root@localhost ~]# vim sum.sh
    [root@localhost ~]# ./sum.sh 
    5
    

    echo

    #!/bin/bash
    sum(){
      echo $(($1 + $2))
    }
    res=$(sum 2 3)
    echo $?,$res
    
    [root@localhost ~]# vim sum.sh
    [root@localhost ~]# ./sum.sh 
    0,5
    

    自定义函数

    #!/bin/bash
    service_index(){
      echo "Usage:servicectl <ServiceName> <start | stop | reload | restart | status>"
      return 1
    }
    service_version(){
      grep "release 7" /etc/centos-release &> /dev/null && echo "centos7"
      grep "release 6" /etc/centos-release &> /dev/null && echo "centos6"
    }
    servicectl(){
      [[ -z $1 || -z $2 ]] && service_index
      [ $(service_version) = "centos7" ] && systemctl $2 ${1}.service || service $1 $2
    }
    
    [root@localhost ~]# vim servicectl.sh
    [root@localhost ~]# source servicectl.sh 
    [root@localhost ~]# servicectl 
    Usage:servicectl <ServiceName> <start | stop | reload | restart | status>
    Unknown operation '.service'.
    Usage: service < option > | --status-all | [ service_name [ command | --full-restart ] ]
    
    [root@localhost ~]# servicectl sshd status
    ● sshd.service - OpenSSH server daemon
       Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
       Active: active (running) since Tue 2019-10-08 03:07:15 CST; 11s ago
         Docs: man:sshd(8)
               man:sshd_config(5)
     Main PID: 3169 (sshd)
       CGroup: /system.slice/sshd.service
               └─3169 /usr/sbin/sshd -D
    
    Oct 08 03:07:15 localhost systemd[1]: Starting OpenSSH server daemon...
    Oct 08 03:07:15 localhost sshd[3169]: Server listening on 0.0.0.0 port 22.
    Oct 08 03:07:15 localhost sshd[3169]: Server listening on :: port 22.
    Oct 08 03:07:15 localhost systemd[1]: Started OpenSSH server daemon.
    
  • 相关阅读:
    HTTP 常见状态码
    SpringMVC 入门
    Maven 整合SSH框架
    SSH 框架整合总结
    Maven 整合SSH框架之pom.xml
    Maven 入门
    WebService 综合案例
    CXF 框架
    jQuery高级
    JavaScript补充:BOM(浏览器对象模型)
  • 原文地址:https://www.cnblogs.com/llife/p/11633416.html
Copyright © 2020-2023  润新知