zoukankan      html  css  js  c++  java
  • 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.
    
  • 相关阅读:
    [LeetCode] 1160. Find Words That Can Be Formed by Characters
    [LeetCode] 561. Array Partition I
    [LeetCode] 942. DI String Match
    [LeetCode] 852. Peak Index in a Mountain Array
    [LeetCode] 461. Hamming Distance
    [LeetCode] 617. Merge Two Binary Trees
    SSM项目实现连接两个mysql数据库
    springboot导入excel到mysql
    Mysql修改表备注, 列信息
    sql.xml where ids in的写法
  • 原文地址:https://www.cnblogs.com/llife/p/11633416.html
Copyright © 2011-2022 走看看